I scoured lots of posts for turning arrays into objects and it looks like there are A LOT of posts doing the reverse of what I'd like. If this is redundant with another post I'd like to see what the title is since I really struggled to find it!
I have two arrays:
let x = [1,2,3]
let y = ["a", "b", "c"]
I want to create an array of objects with keys so that the resulting array looks like:
data = [
{x: 1, y: "a"},
{x: 2, y: "b"},
{x: 3, y: "c"}
]
I tried Object.assign and some other methods but am still struggling (and I'd also like to know what key words I should have used to search if this is already posted since I couldn't find it). Any help appreciated!
You could do that using map with index
let x = [1, 2, 3]; let y = ["a", "b", "c"]; const res = x.map((el, i) => ({ x: el, y: y[i] })); console.log(res);
Why not use a simple for loop
let x = [1,2,3]
let y = ["a", "b", "c"]
let data = [];
for(let i = 0 ; i < x.length; i++){
data.push({x:x[i],y:y[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.