Home > Net >  Create New Object key value pair base on array value
Create New Object key value pair base on array value

Time:10-27

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

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: "",
     },
  ];

CodePudding user response:

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

  • Related