向json对象添加新属性

时间:2016-10-02 07:20:58

标签: javascript jquery json

我有以下格式的JSON对象

[{"field1":1,"field2":"A","field3":"B"},
{"field1":2,"field2":"B","field3":"C"},
{......},
{......},
]

我需要根据一些计算为每一行添加一个新属性。

预期结果

[{"field1":1,"field2":"A","field3":"B","field4"="generatedVal1"},
    {"field1":2,"field2":"B","field3":"C","field4"="generatedVal2"},
    {......},
    {......},
    ]

如何使用javascript实现此目的?

1 个答案:

答案 0 :(得分:2)

使用Array.prototype.forEach方法:

[
  {"field1":1,"field2":"A","field3":"B"},
  {"field1":2,"field2":"B","field3":"C"}
]
.forEach(obj => {
  obj.field4 = 'Something'
})

术语旁注:你没有任何JSON,你有javascript数组(对象)。 JSON是此对象的字符串表示形式,但在您的问题中,您正在讨论对象本身。