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?
我如何做到这一点?
4 个解决方案
#1
2
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 );
#2
1
You can use .map()
:
您可以使用. 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; }
#3
1
You could take a helper object for addressing the types.
您可以使用一个helper对象来处理类型。
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; }
#4
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]});
#1
2
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 );
#2
1
You can use .map()
:
您可以使用. 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; }
#3
1
You could take a helper object for addressing the types.
您可以使用一个helper对象来处理类型。
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; }
#4
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]});