I’m totally unable to figure out how to access the properties and values of objects in an array, specifically using forEach() and/or for-in. (Not map - I tried posting this elsewhere and map was suggested twice. The point is, I want to learn to use forEach and for-in.
Here’s what I had:
var favorites = [
{name: "Adam", color: "red", animal: "horse"},
{name: "Kate", color: "blue", animal: "cat"},
{name: "Jenny", color: "pink", animal: "squirrel"},
{name: "Michael", color: "green", animal: "dog"}];
favorites.forEach(function(obj) {
for (index in obj){
console.log(favorites[index] + favorites[value]);
}
});
I get “value is not defined.” I’ve tried all kinds of variations and have gotten objectObject and the entire contents of an object. How do I access, say, the property “color”? How do I access the value “blue”?
1 Like
inside your forEach loop, you are able to access the current loop’s object through obj.color or obj[“color”]. There is no need for another object loop unless your object is more complex than that.
It is most definitely not defined.
The obj
parameter in your forEach
callback is a single object. The index
variable in your for-in
loop is a key. So,
console.log(obj[index])
is what you are looking for.
1 Like
@PortableStick, I would swear that I had tried the code you suggested a number of times, but I put in what you wrote, and it worked. Thank you, thank you!
@boneyfantaseas, how would I do what you suggested without specifying the property “color”? In other words, by using an index, property name or value variable?
Isn’t that second loop necessary? They are trying to access the properties and their values. forEach only will display the index of current iterator, not the key name.
1 Like
It depends on what was questioned. I answered to the question
So, if you know a key and look for its values, you don’t need the inner loop.
You might need a list of all unique colors. Then you’d maybe use .filter().
You are looking for Object keys, go for Object.keys(obj).
You need to iterate over the object without knowing its keys and output its key/value, use @PortableStick’s answer.
Without knowing the task you can’t tell the correct solution.