1

I did give this a read but it didn't quite help me.

How do I loop through or enumerate a JavaScript object?

I am trying to get the values of the response

response(data.suggestions);

The below is what I get if I console.log(data.suggestions);

(1) [{…}, {…}]
0:
id: "10"
name: "Iron Man"
1:
id: "93"
name: "Purple Dinosaur Inc."

How can I get the values by the keys.

so something like

response(data.suggestions["name"]);
0

2 Answers 2

4

To get the values of the specific names you can iterate over the array and read the name property of the current object.

obje.forEach(x => console.log(x.name))

To store the values in a new array I would recommend using map()

const valArr = obje.map(x => x.name);

const obje = [{
    id: "10",
    name: "Iron Man"

  },
  {
    id: "93",
    name: "Purple Dinosaur Inc."

  }
]

obje.forEach(x => console.log(x.name));
const valArr = obje.map(x => x.name);

console.log(valArr)

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

2 Comments

I like this, it's much cleaner than a simple for-loop but somewhat complicated for beginners.
@Haring10 Agree, but using functional programming in JS has a lot of benefits, writting less code produces less potential misstakes and is easier to read (When you are used to it).
2

This is an array but you are trying to access it as an object.

You need to access the index first.

Use the following:

console.log(data.suggestions[0]["name"]);

That should give you "Iron Man" in this case.

If you want to cycle through them, you can use a for loop.

for(var i = 0; i < data.suggestions.length; i++) {
    console.log(data.suggestions[i]["name"]);
}

This will print out each "name" key from all of your objects in the console.

3 Comments

And how can I go through each of the objects?
So I need to return every objects Name
Thank you. Your answer was super helpful. Much appreciated <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.