如何使用Javascript向数组的每一行添加字段?

时间:2014-07-20 15:12:04

标签: javascript arrays

我有一个javascript变量:

var x = 
{"ab":"x",
 "cd":"y",
 "de":"z",
 "answers":[
    {"answerId":222,"answerUId":1,"text":"x"},
    {"answerId":223,"answerUId":2,"text":"A"},
    {"answerId":224,"answerUId":3,"text":"A"}
 ]
}

如何在一个名为response的answers数组的每个元素中添加一个字段,其值为null?

2 个答案:

答案 0 :(得分:8)

您可以将新属性添加到对象中,例如

x["answers"].forEach(function(currentObject) {
    currentObject["response"] = null;
});

这会遍历每个对象,并为每个对象添加response属性。

答案 1 :(得分:3)

普通javascript:

for (key in x['answers']) {
    x['answers'][key]['response'] = null;
}