0

I have [ { key1:value1, key2:value2 }, { key3:value3, key4:value4 }, .... ]. I want to convert it to { value1: value2, value3: value4 }

2
  • Have a look at Array.reduce and Object.values. Commented Sep 2, 2020 at 0:43
  • Thanks didn't knew about Array.reduce and Object.values Commented Sep 2, 2020 at 1:45

2 Answers 2

1

Use Array#reduce to accumulate your object-data. Foreach object take from the values the first and add a new property with this name to the accumulated object with the value from the second object-value.

let array = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }];

let res = array.reduce((acc, cur) => {
    values = Object.values(cur);
    acc[values[0]] = values[1];
    return acc;
}, {});

console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming the inner objects always have 2 keys:

const arr = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }]

const obj = {};

for (const innerObj of arr) {
  const values = Object.values(innerObj);
  obj[values[0]] = values[1];
}

console.log(obj) // { value1: 'value2', value3: 'value4' }

Note: you're question assumes an order for the keys in the inner objects, but that may not be guaranteed

Comments

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.