1

I need to create one object from array of objects with a a common key present in the objects.

Input

let data = [
    { code: "name", type: "text", value: "abc" },
    { code: "email", type: "email", value: "[email protected]" },
    { code: "username", type: "text", value: "xyz" },
  ];

Expected output

 {
    email: { code: "email" },
    name: { code: "name" },
    username: { code: "username" },
  }

I can iterate through the array using map function and manually create the object. But there should be an easy way of doing it.

3 Answers 3

2

I struggled a bit to find out an elegant solution. But finally achieved

let data = [
    { code: "name", type: "text", value: "abc" },
    { code: "email", type: "email", value: "[email protected]" },
    { code: "username", type: "text", value: "xyz" },
  ];
  
  
let result = data.reduce(
    (accumulatedObject, currentObject) =>
      Object.assign(accumulatedObject, {
        [currentObject.code]: {
          code: currentObject.code,
        },
      }),
    {}
  );
  console.log(result);

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

Comments

0

You could take Object.fromEntries and map the key/value pairs.

let data = [{ code: "name", type: "text", value: "abc" }, { code: "email", type: "email", value: "[email protected]" }, { code: "username", type: "text", value: "xyz" }],
    result = Object.fromEntries(data.map(({ code }) => [code, { code }]));

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

2 Comments

I knew you could come up with something more unreadable ;)))
Can mine be shortened? let result = data.reduce((acc,{code}) => { acc[code] = {code}; return acc},{}); I mean getting rid of the { return acc} part
0

A forEach is simpler than map or reduce

let data = [ { code: "name", type: "text", value: "abc" }, { code: "email", type: "email", value: "[email protected]" }, { code: "username", type: "text", value: "xyz" }, ];       
  
let result = {};
data.forEach(({code}) => result[code] = {code});
console.log(result);

If you must use reduce to save the result assignment, then you can do this which might even be possible to shorten further

let data = [ { code: "name", type: "text", value: "abc" }, { code: "email", type: "email", value: "[email protected]" }, { code: "username", type: "text", value: "xyz" }, ]; 
  
let result = data.reduce((acc,{code}) => { acc[code] = {code}; return acc},{});
console.log(result);

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.