我有: json -
{"names":[{"name": 12,"y": 555}, {"name": 21,"y": 666}, {"name": 35,"y": 777}]}
2)" name"的结构 -
12: "somestring", 21: "somestringlalala", 31:"lallaallla";
所以,我需要用这个结构来改变name的值。在此之后我必须得到 -
{"names":[{"name": "somestring","y": 555}, {"name": "somestringlalala","y": 666}, {"name": "lallaallla","y": 777}]}
我该怎么做? 我知道我可以使用"用于"并检查每个"名称"用if来衡量价值,但我认为这是一种非常新手的方式。
答案 0 :(得分:1)
您可以使用Array#forEach
forEach()
方法为每个数组元素执行一次提供的函数。
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);
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);
答案 1 :(得分:0)