简体   繁体   English

以 2D 格式更改 JSON 响应本机

[英]change JSON in 2D format react native

I have JSON as response from API like this:-我有 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}
    }
},
]

I want to change it like the format I have shown below.我想像下面显示的格式一样更改它。 so I can append in formdata of API:-所以我可以附加在 API 的表单数据中:-

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,
            }
        ]
}
]

how can I do that?我怎样才能做到这一点?
I tried various things but it didn't work for me!!!我尝试了各种方法,但对我不起作用!!!
Thanks!!!谢谢!!!

Use Object.values to get an array of values of the object and use map to iterate and create a new array with it.使用Object.values获取对象值的数组,并使用map迭代并使用它创建一个新数组。

Object.values(JSON).map(data => ({
    ...data.product,
    attribute: Object.values(data.attribute)
}));

You can use array.map with some destructering to spread each object into a new one.您可以使用array.map进行一些破坏每个对象传播到一个新对象中。

 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; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM