Home > Mobile >  Combine the objects inside the array
Combine the objects inside the array

Time:09-13

I have written code where I get all input name, value and create a array of object as below

const productItem = [{"skucode":"1512"},{"name": "Master Tool"},{"qty":"1"},{"skucode":"123"},{"name": "Motor Gear"},{"qty": "1"},{"skucode": "5143"},{"name": "Switch Fits"},{"qty": "1"}]

Now I need help with combining skucode, name qty in object Expected result

const productItem = [{skucode:"1512",name:"Master Tool",qty:"1" },{skucode:"123",name:"Motor Gear",qty:"1" }]

CodePudding user response:

You can use Array.reduce() to combine the items. Each time we get a skucode we create a new object and append succeeding object properties to this.

const productItem = [{"skucode":"1512"},{"name": "Master Tool"},{"qty":"1"},{"skucode":"123"},{"name": "Motor Gear"},{"qty": "1"},{"skucode": "5143"},{"name": "Switch Fits"},{"qty": "1"}]

const result = productItem.reduce((acc, item, idx) => {
    if (item.skucode) { 
        acc.push(item);
    } else {
        acc[acc.length - 1] = { ...acc[acc.length - 1], ...item };
    }
    return acc;
}, []);

console.log(result)
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

I think you are looking for something like this:

let result = productItem.reduce(
  (obj, item) => Object.assign(obj, { [item.key]: item.value }), {});

console.log(result)
  • Related