How Can I Access A Value In A Multidimensional Object With Unique Keys In Javascript?
How can I access the value for name in the object below? Also, does this object have a special name since unique keys (i.e. friend1 and friend2) hold other key/value pairs? var
Solution 1:
for(index in friends ) {
var theFriend =friends[index].name;
alert(theFriend);
}
Maestro please: https://jsfiddle.net/rwoukdpf/
Solution 2:
In ES5, use:
for (var index in friends) { // NB: index and name have function scopevar name = friends[index].name;
}
In ES6, use:
for (let friend of friends) { // NB: 'of', not 'in'let name = friend.name;
}
If you must use a normal for
loop, ensure that your loop invariants are not evaluated in each iteration:
var keys = Object.keys(friends);
for (var i = 0, n = keys.length; i < n; ++i) {
var name = friends[i].name;
}
Even then this loop is not recommended, though - it's cheaper to use a single pass of the object with for .. in
than to create an array of the keys and then iterate through that. The ES6 for .. of
is better still.
Solution 3:
Try following
var keys = Object.keys(friends);
for( i = 0; i < keys.length; i++ ) {
var theFriend = friends[keys[i]].name;
alert(theFriend);
}
For reference - https://jsfiddle.net/mu7jaL4h/7/
Solution 4:
`[i]`
You've just created a new array and put the value of i
in it.
You need to tell JavaScript what object you are accessing the i
property of.
friends[Object.keys(friends)[i]].name
Post a Comment for "How Can I Access A Value In A Multidimensional Object With Unique Keys In Javascript?"