0

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

1 Answer 1

1

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

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

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.