0

I have a JSON variable which looks like this :

{"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"}
]}

I need to push another attribute in each event with javascript and make it look like this:

{"events": [
{"event_id": "1", "event_name": "Breakfast", "event_type": "calendar"},
{"event_id": "1", "event_name": "Calling Bob", "event_type": "calendar"}
]}

3 Answers 3

5

If you have

var obj = {"events": [....

then just use

for (var i = 0; i < obj.events.length; ++i)
    obj.events[i].event_type = "calendar";

Or to optimise:

for (var i = 0, len = obj.events.length; i < len; ++i)
    obj.events[i].event_type = "calendar";
0
3

Convert it to an Object first:

var obj = JSON.parse(theJSON);

for(var i = 0; i < obj.events.length; ++ i)
    obj.events[i].event_type = "calendar";

theJSON = JSON.stringify(obj);
8
  • wtf are you doing? that has nothing to do with the OPs problem. Just push the entry into the array. No need to stringify/parse.
    – Christoph
    Mar 20, 2012 at 13:01
  • 1
    He explicitly said he had JSON to work with, not a JS object.
    – James M
    Mar 20, 2012 at 13:01
  • @Christoph - This is exactly the OPs problem... he does not want to push another element into the array... read the question again. (+1, but consider changing to a normal for loop) Mar 20, 2012 at 13:02
  • for-in iteration over an Array is error-prone, since you can inadvertently touch unrelated fields of the object (consider var a = ["foo"]; a.myField = 3: for-in will pick the "0" and "myField" fields). Mar 20, 2012 at 13:03
  • this code is missing hasOwnProperty and introduces error-prone notation by leaving out the {}, -1 for me...
    – Christoph
    Mar 20, 2012 at 13:04
1
var yourJson = {"events": [
    {"event_id": "1", "event_name": "Breakfast"},
    {"event_id": "1", "event_name": "Calling Bob"}
]};

for(var eventKey in yourJson.events) {
    yourJson.events[eventKey]['event_type'] = 'calendar';
}
2
  • Please see my comment to James McLaughlin's answer for why for-in iteration over an Array is not recommended. Apart from being a bit slower than the usual indexed iteration. Mar 20, 2012 at 13:05
  • thank you for the answer i have learned something new from it .. how to use that fancy for loop :) Mar 20, 2012 at 13:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.