0

I have an array of objects:

[ 
  { key : 'a', value1 : 'a1', value2 : 'a2' },
  { key : 'b', value1 : 'b1', value2 : 'b2' }
];

How do I convert it into the following ?
It would be great to achieve this with lodash.

{
  a: { value1: 'a1', value2 : 'a2' }
  b: { value1: 'b1', value2 : 'b2' }        
}

5 Answers 5

2

You can use the Array.reduce function:

const res = arr.reduce((acc, o) => {
    const {key, ...newO} = o; 
    return {...acc, [o.key]: newO};
  },
  {},
);
Sign up to request clarification or add additional context in comments.

Comments

1

You could destructure the object and map new objects. Finally assign the spreaded objects to a single object.

const
    array = [{ key : 'a', value1 : 'a1', value2 : 'a2' }, { key : 'b', value1 : 'b1', value2 : 'b2' }],
    result = Object.assign({}, ...array.map(({ key, ...o }) => ({ [key]: o })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1

Map the array of objects to an array of [key, rest], where the rest is the original object without the key, and convert to an object using Object.fromEntries(), or lodash's _.fromPairs().

const array = [{ key : 'a', value1 : 'a1', value2 : 'a2' }, { key : 'b', value1 : 'b1', value2 : 'b2' }]

const result = Object.fromEntries(array.map(({ key, ...rest }) => [key, rest]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can achieve it by LODASH

const res = _.chain(array).keyBy('key').mapValues( v => _.omit(v, 'key')).value()

2 Comments

if I wanted to undo this conversion with lodash too, return to the original array of object. can you help with that please.
@MohammadShehab Yes you can do that too. const result = _.map(res, (v, key) => ({ key, ...v })) You can return to the original array by doing the above code one
0

Something like this would work:

const output = {};
[ 
  { key : 'a', value1 : 'a1', value2 : 'a2' },
  { key : 'b', value1 : 'b1', value2 : 'b2' }
].forEach(row => output[row.key] = { value1: row.value1, value2: row.value2 });

1 Comment

I did it like this .. but the number of values could change so I want something more dynamic

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.