问题
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