有条件地基于json标签更改json属性-javascript [英] conditionally change a json property based on a json label - javascript

查看:78
本文介绍了有条件地基于json标签更改json属性-javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载到我的javascript var中的JSON文件

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

在绘制数据之前:

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

我需要将"Value"标签替换为"Value + Year",看起来像这样:9月为"Value2013"​​,4月为"Value2014".

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

从StackOverflow我了解这应该可以在javascript中完成,但我不了解如何为每个条目访问Year的值并将Label值替换为Value + Year

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

谢谢.

推荐答案

这是怎么回事?

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);

请参见 jsFiddle 的控制台,以选择所需的控制台:

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

结果将是:

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


您可以在这里看到不同的常见可能性及其性能结果: http://jsperf.com/jquery-each-vs-underscore-each-vs-for-loops/18

这篇关于有条件地基于json标签更改json属性-javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆