[英]Adding a Object Array in a Array into a JSON
I had this JSON:我有这个 JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:这个对象数组:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?如何使用 Javascript 将对象数组添加到 JSON 内的产品数组中?
Please check this solution of adding objects to object property:请检查这个将对象添加到对象属性的解决方案:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}'; var obj = JSON.parse(jsonStr); obj['event']['products'].push({"name":"Blue Shirt","price":"100"}); obj['event']['products'].push({"name":"Nike Shoes","price":"150"}); jsonStr = JSON.stringify(obj); console.log(jsonStr);
From the look of it, event
is a JSON Array
on its own so to target the first one you will have to pict JSON Object at index 0
.从它的外观来看,
event
本身就是一个JSON Array
,因此要定位第一个,您必须在index 0
处绘制 JSON 对象。
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array现在产品是一个数组,您可以通过迭代对象数组将员工推入其中
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.