[英]How can I merge two arrays and make them array of objects in JavaScript
I have a simple question.我有一个简单的问题。 I have two arrays A and B, I want to return array of object with mixing the two arrays.
我有两个数组 A 和 B,我想通过混合两个数组返回对象数组。
For example:例如:
let a = [ 1, 2 ]
let b = [ 3, 4 ]
Expected result :预期结果:
const C = [
{
a: 1,
b: 3
},
{
a: 2,
b: 4
}
]
How can I do this?我怎样才能做到这一点?
I tried to forloop A then B and assign everytime but it didn't work.我试图 forloop A 然后 B 并每次都分配,但它没有用。
You can use array map method on one of the array and use index
to retrieve the element from the second array您可以在数组之一上使用数组映射方法,并使用
index
从第二个数组中检索元素
let a = [1, 2] let b = [3, 4]; let c = a.map((item, index) => { return { a: item, b: b[index] } }); console.log(c)
Something like this should work:这样的事情应该工作:
let a = [1, 2]; let b = [3, 4]; // From @brk. This transforms each element of a to an object containing a's value and b's value let c = a.map((item, index) => { a: item, b: b[index] }); // Another way. Iterates through each element for (let i = 0; i < a.length; i++) { c[i].a = a[i]; c[i].b = b[i]; } // Yet another. A combination of the first two. for (let [index, item] of Object.entries(a)) { c[index] = { a: item, b: b[index] }; }
There's certainly a more elegant solution, but it evades me at the moment肯定有更优雅的解决方案,但目前它避开了我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.