samedi 4 septembre 2021

how to manipulate json object in javascript

I am trying to manipulate the JSon object below i have given here i need to divid object in to multiple objects based on the qty and warhouse.

 var response =  [
              {
                "name": "test1",
                "qty": 3,    //divid obj to 3 times as qty haing 3 
                "warehouse": {
                  "india": 2,
                  "Usa": 1
                }
              },
              {
                "name": "test2",
                "qty": 1,
                "warehouse": {
                  "india": 1
                }
              } 
            ]

 // here i am trying to manipulate to get the result 
        const finalResponse = response.map(item=>{
              if((item.qty>=1) && (Object.keys(item.warehouse).length >= 1)){
                const warehouses = item.warehouse;
                const arr=[]
                Object.keys(warehouses).forEach((key)=>{
                  if(warehouses[key]>=1){
                    arr.push(...Array(warehouses[key]).fill({...item,[key]:1}))
                  }
                })
                return arr;
              }
            })

here i am trying to get output below but i am not able fine right solution

         finalResponse =[  {
                          "name": "test1",
                          "qty": 1,
                          "india": 1
                        },
                        {
                          "name": "test1",
                          "qty": 1,
                          "india": 1
                        },
                        {
                          "name": "test1",
                          "qty": 1,
                          "Usa": 1
                        },
                        {
                          "name": "test2",
                          "qty": 1,
                          "india": 1
                        }];



Aucun commentaire:

Enregistrer un commentaire