Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading