我的初始数据是这样的..
let initial = {
labels: ['label1', 'label2', 'label3'],
children: ['child1', 'child2', 'child3'],
numbers: [1 , 2 , 3]
};
我需要这种格式的输出..
FINAL_OUTPUT = [
{ labels: 'label1', children: 'child1', numbers: 1 },
{ labels: 'label2', children: 'child2', numbers: 2 },
{ labels: 'label3', children: 'child3', numbers: 3 }
];
将键和值与初始对象分开。但在从相同的对象创建对象数组时感到震惊。请帮忙。
最佳答案
您可以获取条目并将内部数组与给定索引处的值进行映射。
let initial = { labels: ['label1', 'label2', 'label3'], children: ['child1', 'child2', 'child3'], numbers: [1, 2, 3] },
result = Object
.entries(initial)
.reduce((r, [k, a]) => a.map((v, i) => ({ ...(r[i] || {}), [k]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 使用javascript从对象创建对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61311380/