0

For example, the array is:

chipsArray = [{'cheetos':'good'},{'dorritos':'better'}]

Here, chipsArray[0] would give me {'cheetos':'good'}. Let's say I populated this array like the following:

chipsArray.push({[chips]:quality}) 

But now that I'm trying to access the cheetos or dorritos keys in each of objects in this array, I can't. Doing chipsArray[0].chips gives me undefined.

As far as I know when populating the key of an object with a certain value/variable, they should be wrapped in square braces. But how can we extract values from them later on when each of these objects are array indices like the example given above? I tried using Object.keys(chipsArray[index]), but this only gives me the keys whereas I'm trying to extract the specific value for that specific key.

Tl;Dr: How to extract the key of an object inside an array when the keys are strings like this:

chipsArray = [{'cheetos':'good'},{'dorritos':'better'}]

3 Answers 3

1

You could use Object.keys and get only the first element.

var chipsArray = [{ cheetos: 'good' }, { dorritos: 'better' }];

chipsArray.forEach(function (object) {
    var key = Object.keys(object)[0];
    console.log(key, object[key]);
});

Or create an object with the reference to the single objects

var chipsArray = [{ cheetos: 'good' }, { dorritos: 'better' }],
    hash = Object.create(null);

chipsArray.forEach(function (object) {
    hash[Object.keys(object)[0]] = object;
});

console.log(hash['dorritos']['dorritos']);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your suggestion but I mentioned in my question that I tried this way. I don't want the key/keys only. I want the value for a certain key that I need to access. For example: I want to pass the key 'dorritos' to get the value 'better'. I am unable to access it if I do an Object.keys
@BobSilas i think this answer silently implies that when you have the key back, it is fairly easy to get the value (just access to the array with your retreived key)
0

Use the following function. It returns the value by key in the array

function getItemByKey (key, array) {
    var value;
    array.some(function (obj) {
        if (obj[key]) {
            value = obj[key];
            return true;
        }
        return false;
    });
    return value;
}

More about Array.prototype.some here

Comments

0

I think the easiest way is to access the value:

Object.values(chipsArray[i]) 

where i is the index of the array.

Output:

> chipsArray = [{'cheetos':'good'},{'dorritos':'better'}]
[ { cheetos: 'good' }, { dorritos: 'better' } ]
> Object.values(chipsArray[0])
[ 'good' ]

2 Comments

this doesn't work for some reason. Object.keys works just fine but Object.values throws error.
It should. I have included the output also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.