简体   繁体   中英

How to iterate through an array of names and assign each name as a value of a property in an object?

I have this array: var arrayCars = ["Saab", "Volvo", "BMW"];

How can I iterate through it, and assign each car as the value of the property Name in an object with this description: var objectCars = {Name: *insert car*, id: 1234}; .

In the end there should be 3 object. All called objectCars, but the value of Name should be different.

Here is my code, which obviously isn't working:

 var arrayCars = ["Saab", "Volvo", "BMW"]; arrayCars.forEach(function(){ var objectCars = {Name: arrayCars, id:1234}; //Here I am sending that object to a database. No need to worry about that }); 

You can use Array#map()

 var arrayCars = ["Saab", "Volvo", "BMW"].map(c=>({ Name: c, id: 1234 })); console.log(arrayCars); 

First parameter in forEach callback is current value in array loop so you can use it as your object name value.

 var arrayCars = ["Saab", "Volvo", "BMW"]; arrayCars.forEach(function(car) { var objectCars = {Name: car, id:1234}; console.log(objectCars) }); 

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