13garth
13garth

Reputation: 793

Get returned data from Jquery Returned Object for each object

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"]);

Upvotes: 1

Views: 376

Answers (2)

Aalexander
Aalexander

Reputation: 5004

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)

Upvotes: 4

Haring10
Haring10

Reputation: 1557

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.

Upvotes: 2

Related Questions