conditionally change a json property based on a json label - javascript

对着背影说爱祢 提交于 2019-12-12 06:18:21

问题


I have a JSON file which i load into my javascript var

Before plotting my data:

{
    "Month": "September",
    "Value": 1681937,
    "Year": 2013
},
{
    "Month": "April",
    "Value": 2138286,
    "Year": 2014
},

I need to replace the label "Value" with "Value+Year" which will look something like so: "Value2013" for September and "Value2014" for April.

From StackOverflow I understand this should be doable in javascript but i don't understand how to access for every entry the value of Year and replace the Label Value with Value+Year

Thank you in advance.


回答1:


What about this ?

var my = [{
    "Month": "September",
    "Value": 1681937,
    "Year": 2013
}, {
    "Month": "April",
    "Value": 2138286,
    "Year": 2014
}];

console.log('my (before) :', my);

for(var i=0; i<my.length; i++) {
    my[i]["Value" + my[i].Year] = my[i].Value;
    delete my[i]["Value"];
}

console.log('my (after) :', my);

See the console of the jsFiddle to choose the one you need:

Result will be :

[{
    "Month": "September",
    "Value2013": 1681937,
    "Year": 2013
}, {
    "Month": "April",
    "Value2014": 2138286,
    "Year": 2014
}]

EDIT : You can see the different common possibilites and their performance results here : http://jsperf.com/jquery-each-vs-underscore-each-vs-for-loops/18




回答2:


I reccomend using underscore to achieve this smoothly.

Given an array of objects

var myArray=[{
    "Month": "September",
    "Value": 1681937,
    "Year": 2013
},
{
    "Month": "April",
    "Value": 2138286,
    "Year": 2014
}];

Your replacement should be:

_.each(myArray,function(element) { 
    element['Value'+element.Year]=element.Value; 
    delete element.Value; 
});

Resulting array is

[{
    "Month": "September",
    "Value2013": 1681937,
    "Year": 2013
},
{
    "Month": "April",
    "Value2014": 2138286,
    "Year": 2014
}];


来源:https://stackoverflow.com/questions/24144323/conditionally-change-a-json-property-based-on-a-json-label-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!