开发者问题收集

如何在 javascript 中将对象的特定属性制作为对象数组并将其添加到同一对象

2021-09-13
54

我需要将下面的对象数组转换为修改后的对象数组

obj = [{
    org_id: 'CLTINTGBK0001',  
    rate: 8,
    qty: 500,
    total_rate: 35000
  },
  {
    org_id: 'CLTINTGBK0001',  
    rate: 7,
    qty: 800,
    total_rate: 38000
  }
]

目标:

  obj =  [  {
        org_id: 'CLTINTGBK0001',  
       "qty": [
            { 
                "qty": 500,
                "rate":8
            }
        ],
        total_rate: 38000
      },
      {
        org_id: 'CLTINTGBK0001',  
       "qty": [
            { 
                "qty": 800,
                "rate":7
            }
        ],
        total_rate: 38000
      }
    ]

我有下面的代码,但它不起作用。我试图循环对象数组并创建不同的数组和对象,将对象推送到数组并将数组添加到数组的每个对象。

let obj1 = {}
let qrty
let qty = []
for (let i = 0; i < arr.length; i++) {
    qrt1 = arr[i].qty
    rate1 = arr[i].rate
    console.log(qrty)
    obj1.qty = qrt1;
    obj1.rate = rate1;

    qty.push(obj1);
    arr[i].qty = qty
    console.log('arr', arr)
}
3个回答

您可以执行以下操作:

const obj = [{
org_id: 'CLTINTGBK0001',  
rate: 8,
qty: 500,
total_rate: 35000
  },
  {
org_id: 'CLTINTGBK0001',  
rate: 7,
qty: 800,
total_rate: 38000
  }
]

var newObject = []

obj.forEach(element => {

var newElem = {}
for (const [key, value] of Object.entries(element)){
    if(key == 'qty'){
        newElem[key]= {
            qty: element['qty'],
            rate: element['rate'],
        }
    }else if (key == 'rate'){
        continue
    }else{
        newElem[key] = value
    }
}

newObject.push(newElem)
});

console.log(newObject)
Rateb Habbab
2021-09-13

您可以使用 Array#map Destructuring Assignment 来实现此目的:

const obj = [
  { org_id: 'CLTINTGBK0001', rate: 8, qty: 500, total_rate: 35000 },
  { org_id: 'CLTINTGBK0001', rate: 7, qty: 800, total_rate: 38000 },
];

let res = obj.map(({ qty, rate, ...rest }) => ({
  ...rest,
  qty: [{ qty, rate }],
}));

console.log(res);
lejlun
2021-09-13

您可以这样做:

let  obj = [
  { org_id: 'CLTINTGBK0001', rate: 8, qty: 500, total_rate: 35000 },
  { org_id: 'CLTINTGBK0001', rate: 7, qty: 800, total_rate: 38000 }
];

obj = obj.map((item)=> {
  return {
    org_id: item.org_id,
    total_rate: item.total_rate,
    qty:[   {   qty: item.qty, rate:item.rate } ]
  }
});

console.log(obj);
NeNaD
2021-09-13