问题描述
我有一个简单的问题。我有两个数组A和B,我想在混合两个数组的同时返回对象数组。
例如:
let a = [ 1,2 ]
let b = [ 3,4 ]
预期结果:
const C = [
{
a: 1,b: 3
},{
a: 2,b: 4
}
]
我该怎么做?
我尝试先循环A再循环B并每次都分配,但这没用。
解决方法
您可以在其中一个数组上使用数组映射方法,并使用index
从第二个数组中检索元素
let a = [1,2]
let b = [3,4];
let c = a.map((item,index) => {
return {
a: item,b: b[index]
}
});
console.log(c)
,
类似的事情应该起作用:
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]
};
}
肯定有一个更优雅的解决方案,但此刻我回避了