将对象数组转换为Javascript集合的有效方法 [英] Efficient way to convert Object arrays into collection in Javascript

查看:57
本文介绍了将对象数组转换为Javascript集合的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const myObj = {
 a: [1, 2, 3],
 b: [2, 4, 6],
 c: [10, 20, 30]
}

进入

const myCollection = [
  {a: 1, b: 2, c: 10},
  {a: 2, b: 4, c: 20},
  {a: 3, b: 6, c: 30}
]

我尝试了Object.entriesObject.keysmap的组合,但是我总是发现自己在myObj上进行了两次或多次迭代,并且我对自己想出的任何解决方案都不满意. 那么,您认为可以实现这一目标的最有效的方式(就时间复杂度而言)和优雅的方式是什么?

I tried combinations of Object.entries, Object.keys and map but I'm always finding myself iterating twice or more over myObj and I'm not happy with any solution I came up with. So what is the most efficient (in terms of time complexity) and elegant way that you can think to achieve that?

推荐答案

您可以减少条目并映射嵌套数组.

You could reduce the entries and map nested arrays.

const
    object = { a: [1, 2, 3], b: [2, 4, 6], c: [10, 20, 30] },
    result = Object
        .entries(object)
        .reduce((r, [k, a]) => a.map((v, i) => ({ ...r[i], [k]: v })), []);

console.log(result);

这篇关于将对象数组转换为Javascript集合的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆