格式化数组

时间:2017-12-15 11:51:58

标签: javascript arrays formatting

我有一个这样的对象:

[{name:'abcd', data:[1,2,3,4,5,6]},{name:'cdef', data:[7,8,9,10,11,12]}]

我希望将其格式化为:

[{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}, ... ]
请帮忙!

1 个答案:

答案 0 :(得分:1)

您可以使用reduce()forEach()方法。

var data = [{name:'abcd', data:[1,2,3,4,5,6]},{name:'cdef', data:[7,8,9,10,11,12]}]

var result = data.reduce(function(r, {name, data}) {
  data.forEach((e, i) => {
    if(!r[i]) r[i] = {[name]: e};
    else r[i][name] = e;
  })
  return r;
}, [])

console.log(result)