首页 > 解决方案 > 如何在javascript中操作对象数组

问题描述

我正在尝试操作下面给出的对象,我需要根据qtywarehouse属性将对象划分为多个对象。

 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
                }
              },
              {
                "name": "test3",
                "qty": 1,
                "warehouse": {
                }
              } 
            ]

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

在这里,我试图在下面获得输出,但我无法正确解决

         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
                        },,
                     {
                        "name": "test3",
                        "qty": 1,
                        "warehouse": { 
                        }
                        } ];

标签: javascriptarrays

解决方案


const result = []
response.forEach((item) => {
  const { warehouse, qty: _useless, ...rest } = item;
  Object.entries(warehouse).forEach(([key, value]) => {
    const resultItem = {
      ...rest,
      qty: 1, // this is always 1 right?
      [key]: 1, // and this is also 1 always
    }
    result.push(...Array(value).fill(resultItem))
  })
});


// result
[
  { name: 'test1', qty: 1, india: 1 },
  { name: 'test1', qty: 1, india: 1 },
  { name: 'test1', qty: 1, Usa: 1 },
  { name: 'test2', qty: 1, india: 1 }
]

推荐阅读