我有一个从API生成的JSON字符串。
[{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}},{"products":{"product":{"id":"1","Name":"fruit"}}},{"products":{"product":{"id":"2","Name":"pears"}}}]
如何将所有子值推送到父级,看起来像这样。
[{"categories":{"category":[{"id":"1","name":"fruit"},{"id":"2","name":"veg"}]}},{"products":{"products":[{"id":"1","name":"apple"},{"id":"2","name":"pears"}]}}]
感谢。
答案 0 :(得分:0)
您可以创建新对象并使用map来更改数据结构并将该数据分配给新对象。
var data = [{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}}]
var r = {
categories: {
category: data.map(o => o.categories.category)
}
}
console.log(r)
已更新对于新数据结构,您可以使用forEach()
循环并添加到对象。
var data = [{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}},{"products":{"product":{"id":"1","Name":"fruit"}}},{"products":{"product":{"id":"2","Name":"pears"}}}]
var r = {categories: {category: []}, products: {product: []}}
data.forEach(function(e) {
if(e.categories) r.categories.category.push(e.categories.category)
if(e.products) r.products.product.push(e.products.product)
})
console.log(r)
答案 1 :(得分:0)
您可以使用 Array.prototype.reduce()
method ,它会减少单个category
数组中的所有数组项categories
对象,从而获得预期结果
您的代码应如下所示:
var result = data.reduce(function(a, b) {
a[0].categories.push(b.categories);
return a;
}, [{
categories: []
}]);
或者,如果您想要object
而不是array
,请使用以下内容:
var result = data.reduce(function(a, b) {
a.categories.push(b.categories);
return a;
}, {
categories: []
});
<强>演示:强>
var data = [{
"categories": {
"category": {
"id": "1",
"Name": "furit"
}
}
},
{
"categories": {
"category": {
"id": "2",
"Name": "veg"
}
}
}
];
var result = data.reduce(function(a, b) {
a[0].categories.push(b.categories);
return a;
}, [{
categories: []
}]);
console.log(result);
将products
添加到初始对象后进行编辑:
var result = data.reduce(function(a, b) {
if(b.categories)
a[0].categories.push(b.categories);
if(b.products)
a[0].products.push(b.products);
return a;
}, [{
categories: [],
products : []
}]);
<强>演示:强>
var data = [{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}},{"products":{"product":{"id":"1","Name":"fruit"}}},{"products":{"product":{"id":"2","Name":"pears"}}}]
;
var result = data.reduce(function(a, b) {
if(b.categories)
a[0].categories.push(b.categories);
if(b.products)
a[0].products.push(b.products);
return a;
}, [{
categories: [],
products : []
}]);
console.log(result);