我有一个带有值数组的对象
{firstName: ['John', 'Mike']}, lastName: ['Doe', 'Smith']}
,
现在我有一个带有数组的空对象
const newData = {}
newData.ppl = []
如何在ppl
数组中获得此结果,例如:ppl = [{firstName: 'John', lastName: 'Doe'}, {firstName: 'Mike', lastName: 'Smith'}]
答案 0 :(得分:1)
用firstName
迭代Array.forEach()
,并取名字。使用索引从lastName
数组中获取各自的姓氏。将具有名字和姓氏的新对象推送到ppl
数组中。
const data = {firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith']};
const newData = { ppl: [] };
data.firstName.forEach((firstName, i) =>
newData.ppl.push({
firstName,
lastName: data.lastName[i]
})
);
console.log(newData);
答案 1 :(得分:1)
使用Object.entries
,reduce
和forEach
的快速实现:
const srcData = {
firstName: ['John', 'Mike'],
lastName: ['Doe', 'Smith']
};
const ppl = Object
.entries(srcData)
.reduce((acc, [key, values]) => {
values.forEach((val, i) => {
if (i >= acc.length) {
acc.push({});
}
acc[i][key] = val;
});
return acc;
}, []);
console.log(ppl);
说明:
Object.entries
将对象转换为键值对数组。.reduce
迭代地构建结果数组。.forEach
循环从(1)获得的值的数组,如果结果数组的长度不足以容纳所有项目,则将一个空对象推入数组(push({})
)在当前值数组中答案 2 :(得分:0)
您可以获取条目并将属性分配给与数组值相同的索引。
这适用于任意数量的属性。
var data = { firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith'] },
result = Object
.entries(data)
.reduce((r, [k, a]) => (a.forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
使用地图。
let master = {firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith']}
const newData = {};
newData.ppl = master.firstName.map((f,i) => {
return {firstName: f, lastName: master.lastName[i]};
});
console.log(newData.ppl);
答案 4 :(得分:0)
您可以使用Array.reduce()
,Object.values()
和Object.entries()
来做到这一点:
const data = { firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith'] };
const ppl = Object.entries(data).reduce((acc, [key, arr]) => {
arr.forEach((v, i) => (acc[i] = (acc[i] || {}))[key] = v);
return acc;
}, {});
const newData = { ppl: Object.values(ppl) };
console.log(newData);