jfk
jfk

Reputation: 5287

Create one object from a array of objects in Javascript

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.

Upvotes: 1

Views: 61

Answers (3)

mplungjan
mplungjan

Reputation: 177701

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);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

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; }

Upvotes: 0

jfk
jfk

Reputation: 5287

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);

Upvotes: 2

Related Questions