我有一個包含兩個物件的陣列。
我想通過一個鍵 - 分配將兩個物件轉換為一個物件。您可以看到分配欄位現在將它們全部分組。(它變成一個陣列)
從分配:{} 到分配:[]
請問如何實作?
原始陣列
[
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
]
預期陣列
[
{
"allocation": [
{
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
},
{
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
]
}
]
uj5u.com熱心網友回復:
您可以通過以下方式使用 map 方法:
const originalArr = [
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
]
const output = [{"allocation": originalArr.map(item => item.allocation)}]
uj5u.com熱心網友回復:
您可以使用以下方法執行此操作Array.prototype.reduce:
const data = [
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
];
const newData = [data.reduce((acc, curr) => {
acc.allocation.push(curr.allocation);
return acc;
}, { allocation: [] })];
console.log(newData);
uj5u.com熱心網友回復:
只需使用從陣列的每個元素中.map()提取allocation屬性,并將其放入allocation結果的屬性中。
const original = [{
"allocation": {
"name": "custom",
"customAllocations": [{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
];
const result = [{
allocation: original.map(el => el.allocation)
}];
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504327.html
標籤:javascript
