[英]Combine object with array as list of arrays
我有一個對象
var a ={
demo:[1,2,3],
demo1:[test1,test2,test3]
}`
我想將上述對象轉換為對象數組
var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}];`
有人可以幫忙嗎?
使用Array#map函數在第一個數組demo
上進行迭代,然后使用第一項的索引訪問demo1
適當的項。
const a = { demo: [1, 2, 3], demo1: ['test1', 'test2', 'test3'] }; const mapped = a.demo.map((item, index) => ({ demo: item, demo1: a.demo1[index] })); console.log(mapped);
您可以使用array#reduce
遍歷數組,並使用Object#keys()
獲得每個對象的鍵,然后遍歷每個鍵並添加到累加器對象。
var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}], result = a.reduce((r,o) => { Object.keys(o).forEach(k => { r[k] = r[k] || []; r[k].push(o[k]); }); return r; },{}); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.