我有一個這樣的物件陣列:
我有一個這樣的物件陣列。
span class="hljs-keyword">const arr=[
{ name:"test"/span>,
class:3。
},
{ name:"test2",
class:4。
},
{ name:"test3",
class:5。
},]
現在我必須將其轉換為類似地圖的結構,如下所示:
const map={
"name":["test","test2","test3"] 。
"class":[3,4, 5]
}
我對如何制作這種結構毫無頭緒。如果有任何線索,我將非常感激。
uj5u.com熱心網友回復:
如果你有任意數量的鍵,你可以使用Object. entries() 來獲取所有的鍵值對。然后只需在所有條目上回圈,并將它們添加到最終的輸出中。
。const arr=[{name: "test",class:3},{name: "test2",class:4}, {name: "test3",class:5}】。]
const map = arr.reduce((acc, obj) => {
for(const [key, value] of Object.entries(obj)) {
if(acc[key]) {
acc[key].push(value)。
}else{
acc[key] = [value];
}
}
return acc;
}, {});
console.log(map);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
有一個函式接受陣列和你要找的屬性,并使用map為你的新物件的每個屬性回傳一個新的資料陣列。
const arr=[{name: "test",class:3},{name: "test2",class:4}, {name: "test3",class:5}】。]
function getData(arr, prop) {
return arr.map(obj => obj[prop]) 。
}
const map = {
name: getData(arr, 'name')。
class: getData(arr, 'class')
}
console.log(map);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
它應該是這樣的
它應該是這樣的
arr.reduce((res, obj) =>/span> {
Object.entries(obj).forEach(([k,v]/span>) =>{
if(!res[k]) res[k] = [] 。
res[k].push(v)
})
return res
},{})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/306895.html
標籤:
上一篇:在R中建立不一致的字串內的計數?
