我有JSON作为来自API的响应,例如:-
JSON=[
{
product:{"final_price": 500,"customers_basket_quantity": 3,"products_id": 123, "products_name": 'cotton'},
attribute:{
Color:{color:'red',123,color_id:123},
Size:{ size:'XL',size_id:234}
}
},
{
product:{"final_price": 100,"customers_basket_quantity": 5,"products_id": 124, "products_name": 'silk'},
attribute:{
Color:{color:'blue',123,color_id:124}
}
},
]
我想像下面显示的格式一样对其进行更改。所以我可以附加API的formdata:-
product :[
{
"final_price": 500,
"customers_basket_quantity": 3,
"products_id": 123,
"products_name": 'cotton',
'attribute':[
{
'color':'red',
'color_id':123,
},
{
'size':'XL',
'size_id':234,
}
]
},
{
"final_price": 100,
"customers_basket_quantity": 5,
"products_id": 124,
"products_name": 'silk',
'attribute':[
{
'color':'blue',
'color_id':124,
}
]
}
]
我该怎么做?
我尝试了各种方法,但对我没有用!!
谢谢!!!
答案 0 :(得分:1)
使用Object.values获取对象的值数组,并使用map迭代并创建一个新数组。
Object.values(JSON).map(data => ({
...data.product,
attribute: Object.values(data.attribute)
}));
答案 1 :(得分:1)
您可以将array.map与某些destructering结合使用,spread将每个对象变成一个新对象。
const data=[{product:{final_price:500,customers_basket_quantity:3,products_id:123,products_name:"cotton"},attribute:{Color:{color:"red",color_id:123},Size:{size:"XL",size_id:234}}},{product:{final_price:100,customers_basket_quantity:5,products_id:124,products_name:"silk"},attribute:{Color:{color:"blue",color_id:124},Size:{size:"XL",size_id:234}}}];
const result = data.map(({product, attribute, ...rest}) => {
return {
...product,
attribute: Object.values(attribute),
...rest
};
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; };