循环遍历json数组并使用javascript添加到每个对象

时间:2018-02-10 22:48:10

标签: javascript arrays json

你好假设我有以下json数组:(继承人数组中的前3个)

var data = [
                {
                    "percent_change_1h": "2.19",
                    "percent_change_24h": "-1.07",
                    "percent_change_7d": "-7.2",
                },
                {
                    "percent_change_1h": "1.96",
                    "percent_change_24h": "-2.13",
                    "percent_change_7d": "-11.64",
                },
                {
                    "percent_change_1h": "9.21",
                    "percent_change_24h": "18.31",
                    "percent_change_7d": "18.3",
                }
            ]

如何遍历此数据,并为每个数据集添加一个对象,以便在执行循环后,它将如下所示:

var data = [
                {
                    "percent_change_1h": "2.19",
                    "percent_change_24h": "-1.07",
                    "percent_change_7d": "-7.2",
                    "new_key": "newvalue"
                },
                {
                    "percent_change_1h": "1.96",
                    "percent_change_24h": "-2.13",
                    "percent_change_7d": "-11.64",
                    "new_key": "newvalue"
                },
                {
                    "percent_change_1h": "9.21",
                    "percent_change_24h": "18.31",
                    "percent_change_7d": "18.3",
                    "new_key": "newvalue"
                }
            ]

我使用for key in data循环以及forEach函数搞砸了,我无法理解它。任何帮助,将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:2)

一个简单的循环就行了。尝试方便的for..of语法:

for (const o of data) o.new_key = "newvalue";

答案 1 :(得分:1)

使用map()

data = data.map(d => ({...d, new_value: "newvalue"}));



var data = [
  {"percent_change_1h": "2.19",},
  {"percent_change_1h": "1.96",}
];

data = data.map(d => ({...d, new_value: "newvalue"}));

console.log(data);




答案 2 :(得分:1)

尝试循环trow对象然后添加newval,请参阅此函数:

var data = [
                {
                    "percent_change_1h": "2.19",
                    "percent_change_24h": "-1.07",
                    "percent_change_7d": "-7.2",
                },
                {
                    "percent_change_1h": "1.96",
                    "percent_change_24h": "-2.13",
                    "percent_change_7d": "-11.64",
                },
                {
                    "percent_change_1h": "9.21",
                    "percent_change_24h": "18.31",
                    "percent_change_7d": "18.3",
                }
            ]

function addValue(data,vals)
{
  for(var inc = 0;inc < data.length ; inc++)
  {
    data[inc]['newval'] = vals;
   }
   return data;
}

console.log(addValue(data,'newval'));
.as-console-wrapper {
    bottom: auto;
    max-height: 100%;
    top: 0;
}