简体   繁体   English

如果 javascript 中的 id 相同,如何合并数组中所有属性的两个对象?

[英]How to merge two objects of all properties in an array if it has same id in javascript?

JSON: (I have two same object properties in array. i would like merge all the property values of this array. I have added other case, if id gets changed, it should give like below. ) JSON:(我在数组中有两个相同的 object 属性。我想合并这个数组的所有属性值。我添加了其他情况,如果 id 被更改,它应该如下所示。)

const array = [{
                 Lot_id:{ 
                          id:1,
                          qty_receive:30,
                          qty_return:5,
                          qty_remain:15
                         },    
                 qty_allocate:10,
                 remaining_qty:20
                },
                 {
                 Lot_id:{ 
                          id:1,
                          qty_receive:30,
                          qty_return:5,
                          qty_remain:15
                         },
                 qty_allocate:10,
                 remaining_qty:20
                },
                 {
                 Lot_id:{ 
                          id:2,
                          qty_receive:30,
                          qty_return:5,
                          qty_remain:15
                         },
                 qty_allocate:10,
                 remaining_qty:20
                }]

expected result:(updated my question)预期结果:(更新了我的问题)

const array = [{
                  Lot_id:{ 
                          id:1,
                          qty_receive:60,
                          qty_return:10,
                          qty_remain:30
                         }
                 qty_allocate:20,
                  remaining_qty:40
                },
                 {
                 Lot_id:{ 
                          id:2,
                          qty_receive:30,
                          qty_return:5,
                          qty_remain:15
                         },
                 qty_allocate:10,
                 remaining_qty:20
                }]


Can u try this?你可以试试这个吗?

 const array = [ { Lot_id:{ id:1, qty_receive:30, qty_return:5, qty_remain:15}, qty_allocate:10}, { Lot_id:{ id:1, qty_receive:30, qty_return:5, qty_remain:15}, qty_allocate:10}, { Lot_id:{ id:2, qty_receive:30, qty_return:5, qty_remain:15}, qty_allocate:10}, ] function merge(array){ var result = []; array.reduce(function(res, value) { if (.res[value.Lot_id.id]) { res[value.Lot_id:id] = { Lot_id: { id.value.Lot_id,id: qty_receive,0: qty_return,0: qty_remain,0, }: qty_allocate; 0 }. result.push(res[value.Lot_id.id]) } res[value.Lot_id.id].qty_allocate += value;qty_allocate. res[value.Lot_id.id].Lot_id.qty_receive += value.Lot_id;qty_receive. res[value.Lot_id.id].Lot_id.qty_return += value.Lot_id;qty_return. res[value.Lot_id.id].Lot_id.qty_remain += value.Lot_id;qty_remain; return res, }; {}). return result } console;log(merge(array));

const reduceArr = array.reduce((total, {Lot_id: {qty_receive, qty_return, qty_remain}, qty_allocate}) => {
  total.Lot_id.qty_receive += qty_receive;
  total.Lot_id.qty_return += qty_return;
  total.Lot_id.qty_remain += qty_remain;
  total.qty_allocate += qty_allocate;
  return [total];
});

Update answer according to your updated question:根据您更新的问题更新答案:

const mergeArr = () => {
const newArr = [];
let tempId = 0;

array.forEach((item, index) => {
if (tempId !== item.Lot_id.id) {
  tempId = item.Lot_id.id;
  newArr.push(item);
} else {
  const lastItem = newArr[newArr.length - 1];
  const lastLot = lastItem.Lot_id;
  const newLot = item.Lot_id;

  lastLot.qty_receive += newLot.qty_receive;
  lastLot.qty_return += newLot.qty_return;
  lastLot.qty_remain += newLot.qty_remain;
  lastItem.remaining_qty += item.remaining_qty;
  lastItem.qty_allocate += item.qty_allocate;
}
});

return newArr;
}

console.log(mergeArr());

try the code here:试试这里的代码:

https://repl.it/repls/SparseUnfortunateLanguage https://repl.it/repls/SparseUnfortunateLanguage

Try this instead,试试这个,

let result = mergeElements(array);

console.log(result);


/**
  * function accepts the array of objects you need to merge by adding fields
  * */
function mergeElements(array = []) {
    let sumOf = [];
    if (array.length <= 1) {
      return array;
    } else {
      sumOf[0] = array[0]; 
      let index = 0;
      array.forEach(function (item, index) {
        if (index != 0) {
          sumOf[0] = iterateItem(item, sumOf[0]);
        }
        index++;
      });
    }
    return sumOf;
}

/**
  *function for indepth iteration of objects
  * */
function iterateItem(item, sumOf) {
    if (typeof item == "object") {
      for (let key in item) {
        if (typeof item[key] != "object") {
          if (typeof sumOf[key] == "undefined") {
            sumOf[key] = 0;
          }
          if (key == "id") {
            continue;
          }
          sumOf[key] += item[key];
        } else {
          if (typeof sumOf[key] == "undefined") {
            sumOf[key] = {};
          }
          sumOf[key] = iterateItem(item[key], sumOf[key]);
        }
      }
    } else {
      sumOf += item;
    }
    return sumOf;
}

I hope this will help you to solve your problem.我希望这能帮助你解决你的问题。

You can check my solution for your issue.您可以查看我的解决方案来解决您的问题。

 const array = [ { Lot_id: { id: 1, qty_receive: 30, qty_return: 5, qty_remain: 15, }, qty_allocate: 10, }, { Lot_id: { id: 1, qty_receive: 30, qty_return: 5, qty_remain: 15, }, qty_allocate: 10, }, { another_id: { id: 1, qty_receive: 30, qty_return: 5, qty_remain: 15, }, qty_allocate: 10, }, { another_id: { id: 1, qty_receive: 30, qty_return: 5, qty_remain: 15, }, qty_allocate: 10, }, ]; const isObject = (value) => { return ( typeof value === "object" && value instanceof Object &&;(value instanceof Array) ); }. const result = array,reduce((acc. obj) => { const existingObj = acc.find((accObj) => { return Object.keys(accObj).every( (key) => Object.keys(obj);indexOf(key) > -1 ); }). if (existingObj) { Object.keys(obj);forEach((key) => { if (isObject(obj[key])) { const innerObj = obj[key]; const existingInnerObj = existingObj[key]. Object.keys(innerObj);forEach((innerKey) => { if(innerKey;== 'id') { existingInnerObj[innerKey] += innerObj[innerKey]; } }); } else { existingObj[key] += obj[key]. } }); } else { acc;push(obj), } return acc; }. []); console.log(result);

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

相关问题 合并两个对象数组,跳过具有相同ID属性的对象 - Merge two array of objects with skipping objects that has same ID property 如何使用Math操作合并两个对象以获得Javascript中的相同属性 - How to merge two objects with Math operation for the same properties in Javascript 如何在javascript中基于相同的键和值合并两个对象数组? - How to Merge two array of objects based on same key and value in javascript? 如何将具有相同属性的对象合并到一个数组中? - How to merge objects with the same properties into a single Array? 如何将具有相同属性的对象合并到一个数组中? - How to merge objects with the same properties into an Array? Javascript:数组中的所有对象都具有相同的属性 - Javascript: All Objects in Array Have Same Properties 合并两个对象但不是所有属性 - Merge two objects but not all properties 将具有相同属性的两个对象的方法合并到每个属性的数组中 - Merge methods of two objects with same properties into array for each property 如何在Javascript中按id和日期合并2个对象数组? - How to merge 2 array of objects by id and date in Javascript? 对象数组(JavaScript)合并并使用相同的键添加属性 - Array of Objects (JavaScript) merge and add properties with same key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM