How to push elements in JSON from javascript array

3

I want to add javascript array values into JSON values object. The other element is also replaced my element like recipients, subject, message. I got Json like:

enter image description here

Below is my code.

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY = JSON.stringify({values: values});
alert(BODY);

This question is tagged with javascript jquery arrays json

~ Asked on 2013-09-28 07:22:08

The Best Answer is


13

I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent (because you are using jQuery/tagged) method after prepare the object from array

var BODY = {
    "recipients": {
        "values": []
    },
    "subject": 'TitleOfSubject',
    "body": 'This is the message body.'
}

var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
    var item1 = {
        "person": { "_path": "/people/"+names[ln] }
    };
    values.push(item1);
}

// Now merge with BODY
$.extend(BODY.recipients.values, values);

DEMO.

~ Answered on 2013-09-28 08:10:09


0

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

~ Answered on 2013-09-28 07:40:34


Most Viewed Questions: