![](/img/trans.png)
[英]How can I group objects alphabetacally within an array by a specific key?
[英]How to group an array of objects by a specific key
我有一个包含两个对象的数组。
我想通过一个键分配将两个对象转换为一个 object。 您可以看到分配字段现在将它们全部分组。 (它变成一个数组)
从分配:{} 到分配:[]
请问如何实现?
原始数组
[
{
"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
}
]
}
]
}
]
你可以使用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);
只需使用.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);
您可以通过以下方式使用 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)}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.