0
            [{ date="4/7/2012",  username="dealcloud",  user_id=304378189},
             { date="4/7/2012",  username="rizwanharun",  user_id=18932327
            },{ date="4/7/2012",  username="aimtoendhunger",  user_id=
            122384145},{ date="4/7/2012",  username="Sindy882",  user_id=
            705160297}}]

how can I insert a new object with variable and value by the end of each object. e.g i want to put location like date,username,user_id,location in each object

cheers for the help

2 Answers 2

2

Note: Your json syntax is wrong.

You can do something like this

var jsonObj = [{ "date":"4/7/2012",  "username":"dealcloud",  "user_id":304378189},
             { "date":"4/7/2012",  "username":"rizwanharun",  "user_id":18932327
            },{ "date":"4/7/2012",  "username":"aimtoendhunger",  "user_id":
            122384145},{ "date":"4/7/2012",  "username":"Sindy882",  "user_id":
            705160297}}];
for(var i = 0; i < jsonObj.length;i++) {
    jsonObj[i].location = "New location";
}
Sign up to request clarification or add additional context in comments.

2 Comments

but there is no location keys in the array. wont i have to create those first and after putting the values inside?
@anjelos even there was no 'location' key initially, javascript allows you to add it later.
1

remember that Objects doesn't have an order.

var ary = [{}, {}, {}];

for (i in ary) {
  ary[i]['new_key'] = 'new val';
}

2 Comments

no when i do console.log it gives me an empty array. as i said from below the location key is not in any of the objects of the array.i have to create it first
to add a new key inside a JS Object all you have to do is var a = {}; a['my_new_key'] = 'value';. If you need to add a new object to an array use Array#push() MDN

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.