Conditionally Change A Json Property Based On A Json Label - Javascript
I have a JSON file which i load into my javascript var Before plotting my data: { 'Month': 'September', 'Value': 1681937, 'Year': 2013 }, { 'Month': 'April', 'V
Solution 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;
deletemy[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
Solution 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
}];
Post a Comment for "Conditionally Change A Json Property Based On A Json Label - Javascript"