我需要使用JavaScript将对象数组转换为简单对象数组
下面我将当前代码与当前输出放在一起
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const a = result.map(item => {
return Object.assign({}, ...item)
})
console.log(a)
上述代码的输出(当前和错误输出)
[ { "name": "2" }, { "name": "4" }, { "name": "5" }, { "name": "6" } ]
预期和所需的输出
[
{
name: '1'
},
{
name: '2'
},
{
name: '3'
},
{
name: '4'
},
{
name: '5'
},
{
name: '6'
}
]
答案 0 :(得分:4)
看起来您正在寻找flat
(mdn)
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const a = result.flat();
console.log(a)
答案 1 :(得分:1)
有一种简单且受广泛支持的方法,无需使用flat
即可使阵列变平-使用reduce
和push
(为提高效率,不使用concat
)。
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const a = result.reduce((acc, curr) => (acc.push(...curr), acc));
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5语法:
var result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
var a = result.reduce(function(acc, curr) {
return (Array.prototype.push.apply(acc, curr), acc);
});
console.log(a);
答案 2 :(得分:0)
您可以使用Array.prototype.concat合并数组。
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const b = Array.prototype.concat.apply([], result);
console.log(b);