gpt4 book ai didi

javascript - 使用 javascript 更新后替换 JSON 对象

转载 作者:行者123 更新时间:2023-12-03 07:26:01 29 4
gpt4 key购买 nike

这是 JSON replacement 的后续问题 我无法得到适当的回应。因此,我用一个更好的例子来发布这个问题。

var beforeReplacement=[
{
"Name": "app1",
"id": "1",
"groups": [
{
"id": "test1",
"name": "test grp45",
"desc": "this is a test group"
},
{
"id": "test2",
"name": "test group 2",
"desc": "this is another test group"
}
]
},
{
"Name": "app2",
"id": "2",
"groups": [
{
"id": "test3",
"name": "test group 4",
"desc": "this is a test group"
},
{
"id": "test4",
"name": "test group 4",
"desc": "this is another test group"
}
]
}
]


changed object:
[
{
"Name": "app2",
"id": "2",
"groups": [
{
"id": "test3",
"name": "changed test group 4",
"desc": "this is a test group"
}

]
}
]





var afterReplacement=[
{
"Name": "app1",
"id": "1",
"groups": [
{
"id": "test1",
"name": "test grp45",
"desc": "this is a test group"
},
{
"id": "test2",
"name": "test group 2",
"desc": "this is another test group"
}
]
},
{
"Name": "app2",
"id": "2",
"groups": [
{
"id": "test3",
"name": "changed test group 4",
"desc": "this is a test group"
},
{
"id": "test4",
"name": "test group 4",
"desc": "this is another test group"
}
]
}
]

我已经更改了 var beforeReplacement 中的名称,并提到了更改后我将收到的修改后的对象。如何在 beforeReplacement 中有效地替换此更改的对象,以便生成的对象类似于 var afterReplacement

最佳答案

var afterReplacement = beforeReplacement.map(function (af) {
for(var i in changed) {
if (changed[i].id != af.id) continue;

af = changed[i];
break;
}
return af;
});

关于javascript - 使用 javascript 更新后替换 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36004267/

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