Search code examples
javascriptarraysobjectfilterreduce

Combine the objects inside the array


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" }]


Solution

  • 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; }