jQuery 如何从javascript数组推送JSON中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19064487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to push elements in JSON from javascript array
提问by deepak bhardwaj
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:
我想将 javascript 数组值添加到 JSON 值对象中。另一个元素也替换了我的元素,如收件人、主题、消息。我得到了 Json:
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);
回答by The Alpha
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
我认为您想从数组中创建对象并将其与旧对象(BODY.recipients.values)结合,如果是这样,那么您可以在从数组中准备对象后使用$.extent
(因为您正在使用jQuery
/标记)方法来完成它
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);
回答by ComFreek
You can directly access BODY.values
:
您可以直接访问BODY.values
:
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
BODY.values.push(item1);
}
回答by Radney Aaron Alquiza
If you want to stick with the way you're populating the values array, you can then assign this array like so:
如果你想坚持填充 values 数组的方式,你可以像这样分配这个数组:
BODY.values = values;
after the loop.
循环后。
It should look like this:
它应该是这样的:
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.values = values;
alert(BODY);
JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.
一旦您将 JSON.stringify() 作为参数传递给 AJAX 调用,它就会很有用。请记住:您的 BODY 对象中的 values 数组与 var values = [] 不同。您必须将该外部值 [] 分配给 BODY.values。这是 OOP 的优点之一。
回答by Rajesh kumar
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item