我有一个这样的对象:
[{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}, ... ]
请帮忙!
答案 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)