javascript - 使用javascript从对象创建对象数组?

标签 javascript arrays multidimensional-array lodash javascript-objects

我的初始数据是这样的..

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/

相关文章:

javascript - 循环中的正则表达式

javascript - 为什么这个更具体的 CSS 规则没有胜出?

php - 如何区分2个多维数组?

javascript - 即使 if 语句为 true,else 条件也始终被执行

javascript - .live 不是 rails 3.2.11 中的函数错误

python - 如何将 numpy 数组附加到不同大小的 numpy 数组?

c++ - 在结构 C++ 之间传递数组

JavaScript Float32Array 检查可转移对象是否已绝育

javascript - 在javascript中创建多维数组

arrays - 如何更改二维数组的大小