[英]Convert arrays to values (with keys!) in an array of objects
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.我搜索了很多将 arrays 变成对象的帖子,看起来有很多帖子与我想要的相反。 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:我有两个 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).我尝试了 Object.assign 和其他一些方法,但仍在苦苦挣扎(而且我还想知道如果由于找不到它已经发布,我应该使用哪些关键词进行搜索)。 Any help appreciated!
任何帮助表示赞赏!
You could do that using map with index您可以使用带有索引的 map 来做到这一点
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为什么不使用简单的 for 循环
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]});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.