gpt4 book ai didi

javascript - 如何重新组织 json 数据?

转载 作者:行者123 更新时间:2023-11-27 22:52:45 26 4
gpt4 key购买 nike

我有:json -

{"names":[{"name": 12,"y": 555}, {"name": 21,"y": 666}, {"name": 35,"y": 777}]}  

2) “名称”的结构 -

12: "somestring", 21: "somestringlalala", 31:"lallaallla";

所以,我需要用这个结构更改名称的值。在此之后我必须得到 -

{"names":[{"name": "somestring","y": 555}, {"name": "somestringlalala","y": 666}, {"name": "lallaallla","y": 777}]}

我该怎么做?我知道我可以使用“for”并使用 if 检查每个“name”值,但正如我认为的那样,这是非常新手的方式。

最佳答案

您可以使用Array#forEach

The forEach() method executes a provided function once per array element.

var data = { "names": [{ "name": 12, "y": 555 }, { "name": 21, "y": 666 }, { "name": 35, "y": 777 }] },
replacements = { 12: "somestring", 21: "somestringlalala", 31: "lallaallla" };

data.names.forEach(function (a) {
a.name = replacements[a.name];
});

console.log(data);

ES6 带有 arrow function expression

var data = { "names": [{ "name": 12, "y": 555 }, { "name": 21, "y": 666 }, { "name": 35, "y": 777 }] },
replacements = { 12: "somestring", 21: "somestringlalala", 31: "lallaallla" };

data.names.forEach(a => a.name = replacements[a.name]);

console.log(data);

关于javascript - 如何重新组织 json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37927719/

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