Some Berry Some Berry - 5 months ago 32
Javascript Question

How can i reorganize json data?

I have:
json -

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


2) structure for "name" -

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


So, i need to change value of name with this structure. After this i must get -

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


How can i do this?
I know that i can use "for" and check every "name" value with if, but it's very newbie way, as i think.

Answer

You could use 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 with 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);