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"
}
]
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?
Share Improve this question edited Apr 19, 2018 at 23:51 georgeawg 49k13 gold badges77 silver badges98 bronze badges asked Apr 19, 2018 at 14:25 HKI345HKI345 3133 gold badges8 silver badges24 bronze badges 1- I was actually looking for the opposite of this .ie. I have an array of objects and want to split the 2 properties into 2 different arrays. Any idea please ? – Nikhil Nanjappa Commented Sep 6, 2019 at 9:52
4 Answers
Reset to default 6Use 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 );
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]});
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; }