gpt4 book ai didi

javascript - 用javascript中另一个对象的值创建新对象

转载 作者:行者123 更新时间:2023-12-02 14:37:11 25 4
gpt4 key购买 nike

我们如何使用 JavaScript 更改以下数据对象的结构。需要将所有名称分类到std下。提前致谢

[
{
"name": "Rohan",
"std": "3"
},
{
"name": "Jack",
"std": "2"
},
{
"name": "Peter",
"std": "2"
}
]

[
{
"std": "2",
"details": [
{
"name": "Jack"
},
{
"name": "Peter"
}
]
},
{
"std": "3",
"details": [
{
"name": "Rohan"
}
]
}
]

最佳答案

使用Array.forEachArray.mapObject.keys函数的解决方案:

var arr = [{"name": "Rohan", "std": "3"}, { "name": "Jack", "std": "2" }, { "name": "Peter", "std": "2" }],
grouped = {}, result;

arr.forEach(function(obj){
var std = obj['std'];
if (this[std]) {
this[std]['details'].push({'name' : obj['name']});
} else {
this[std] = {'std' : std, 'details' : [{'name' : obj['name']}]};
}
}, grouped);
result = Object.keys(grouped).map((k) => grouped[k]);

console.log(JSON.stringify(result, 0, 4));

输出:

[
{
"std": "2",
"details": [
{
"name": "Jack"
},
{
"name": "Peter"
}
]
},
{
"std": "3",
"details": [
{
"name": "Rohan"
}
]
}
]

关于javascript - 用javascript中另一个对象的值创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37359385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com