简体   繁体   中英

Create an array of objects with multiple properties using javascript

How to create an array of objects that has two properties name and shade ?

 [{ "name": "black", "shade": "dark" }, { "name": "white", "shade": "light" }, { "name": "red", "shade": "dark" }, { "name": "blue", "shade": "dark" }, { "name": "yellow", "shade": "light" } ] 

I have two different arrays now.

name = ["black","white","red","blue","yellow"]
shade = ["dark","light","dark","dark","light"]

How can I achieve this?

Use map

var output = name.map( (s, i) => ({name : s, shade : shade[i]}) );

Demo

 var name1 = ["black","white","red","blue","yellow"]; var shade = ["dark","light","dark","dark","light"]; var output = name1.map( (s, i) => ({name : s, shade : shade[i]}) ); console.log( output ); 

You can use .map() :

 let names = ["black", "white", "red", "blue", "yellow"], shades = ["dark", "light", "dark", "dark", "light"]; let merge = (a1, a2) => names.map((n, i) => ({name: n, shade: shades[i]})); console.log(merge(names, shades)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You could take a helper object for addressing the types.

 var names = [ "black", "white", "red", "blue", "yellow"], shades = ["dark", "light", "dark", "dark", "light"], temp = { name: names, shade: shades }, result = Object .keys(temp) .reduce( (r, k) => (temp[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), [] ); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

var new_array = [];
// assuming the arrays have the same length
for (var i = 0; i < name.length; i++)
    new_array.push({name: name[i], shade: shade[i]});

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