Home > database >  How do i transform an array of object into just one object?
How do i transform an array of object into just one object?

Time:08-06

I have an array of objects that I need to transform into objects with key names which is {key}{index)

const input = [
    {
        data: 'Abc',
        quantity: '1'
    },
    {
        data: 'Def',
        quantity: '2'
    },
    // ...
]

Below is an example of the output where the index would be appended to the key name which results in data1, quantity1, data2, quantity2..

const output = { data1: 'Abc', quantity1: 1, data2: 'Def', quantity2: 2 }

CodePudding user response:

Use reduce:

const result = input.reduce((acc, item, index) => {
    let {data, quantity} = item;
    
    // (index   1) because obviously the index is 0-based, and in
    // your example you started from 1
    acc["data"   (index   1)] = data;
    acc["quantity"   (index   1)] = quantity;

    return acc;
}, {});

CodePudding user response:

Try this:

const result = input.reduce((obj, item, index) => {
        Object.keys(item)
        .forEach(key=>{
            obj[key (index 1)] = item[key]
        })
    return obj;
}, {});
  • Related