-1

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 }

2 Answers 2

2

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;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.