js 怎样数组对象转对象数组

新手上路,请多包涵

原数据:
{key1:[0,1,2,3,4,5],
key2:[0,1,2,3,4,5],
key3:[0,1,2,3,4,5]}

目标数据:
[{key1:0,key2:0,key3:0},
{key1:1,key2:1,key3:1},
{key1:2,key2:2,key3:2},
{key1:3,key2:3,key3:3},
{key1:4,key2:4,key3:4},
{key1:5,key2:5,key3:5}]

求大神使用JavaScript搞一下,拜托!

阅读 2.5k
2 个回答
// 考虑到原始数据中的数组的长度和内容都不定
const o1 = {
  key1:[0,1,2,3,4,5],
  key2:[0,1,2,3,4,5],
  key3:[0,1,2,3,4,5]
}

const o2 = {
  key1:[0,1,2,3,5],
  key2:[0,1,2,3,4,5,6],
  key3:[0,1,3,4,5,8,9]
}

const trans = o => Array
// 取所有数组的交集并去重
  .from(new Set(Object.values(o)
  .reduce((ret, arr) => ret.concat(arr))))
// map 成目标数据结构
  .map(it => Object
    .keys(o)
    .reduce((ret, key, index) => o[key].includes(it)
      ? {...ret, [`${key}`]: it}
      : ret, {}))

console.log(trans(o1))
console.log(trans(o2))   
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏