1

I have a javascript variable:

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"}
 ]
}

How can I add a field to each element of the answers array called response with a value of null ?

2 Answers 2

8

You can add the new property to the objects, like this

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

This iterates through each and every object and adds the response property to each of them.

Sign up to request clarification or add additional context in comments.

3 Comments

forEach is native javascript
@Otanaught It just requires a browser that supports ECMAScript 5.1: Array.prototype.forEach
Oh i see, just checked the MDN about forEach. Watch out for browser backwards compatibility.
3

Plain javascript:

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

4 Comments

Iterating an array with for..in is bad.
@thefourtheye could you please explain why?
Just check the boxed items in this section
@thefourtheye - The caution in the boxed items recommends against using for..in only "where index order is important". I don't see that index order is important here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.