Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create New Object key value pair base on array value

I need to generate csv for my client data but I need to include all headers came from my models.

The problem is some of my old client data has no existing fields. I want to create a new object with all the headers as a key and leave some empty string if a client has no data or no existing fields. Thanks for helping!

Here example of headers as key

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let header = ["firstname", "lastname", "age", "gender", "address"];

Example for client info

let userInfo = [
   {
      firstname: "John",
      lastname: "Doe",
      age: "20",
      gender: "male",
    },
    {
      firstname: "Jane",
      lastname: "Doe",
    },
  ];

Expected Output

let userInfo = [
    {
       firstname: "John",
       lastname: "Doe",
       age: "20",
       gender: "male",
       address: "",
     },
     {
       firstname: "Jane",
       lastname: "Doe",
       age: "",
       gender: "",
       address: "",
     },
  ];

>Solution :

you can create an empty object with array.reduce

const emptyObj = header.reduce((acc, key) => {
  acc[key] = "";
  return acc;
}, {});

and use array.map on userInfo to return an object that concat the empty object with the one with value

let header = ["firstname", "lastname", "age", "gender", "address"];
let userInfo = [{
    firstname: "John",
    lastname: "Doe",
    age: "20",
    gender: "male",
  },
  {
    firstname: "Jane",
    lastname: "Doe",
  },
];

const emptyObj = header.reduce((acc, key) => {
  acc[key] = "";
  return acc;
}, {});


const result = userInfo.map(user => {
  return {
    ...emptyObj,
    ...user
  };
})
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading