简体   繁体   中英

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM