Home > database >  Push multiple objects to an already initialized, empty object array
Push multiple objects to an already initialized, empty object array

Time:07-28

People is my model, data is my new information, and the forEach is how I am trying to insert the new data into my model, but formatted to only the information I care about

people = [{name: '', age: 0}];

data = [
  {id: '123', name: 'Bob', lastName: 'Guy', age: 40}, 
  {id: '321', name: 'Michael', lastName: 'Park', age: 20}, 
]

data.forEach(person => {
   people.push({
      name: person.name,
      age: person.age,
   });
});

However, the result I get is this:

people = [
  {name: '', age: 0}, 
  {name: 'Bob', age: 40}, 
  {name: 'Michael', age: 20}
];

I'm trying to have the object array look like this instead:

people = [
  {name: 'Bob', age: 40}, 
  {name: 'Michael', age: 20}
];

However, I would like to know if theres a way to do it without an extra line of code (like popping the first element), and if theres a way to do it in one command? If not, I am open to suggestions. Thank you!

CodePudding user response:

You're using the original array and not only that but also you're mutating the array.

You can use the function Array.prototype.map in order to generate a new array with the desired data.

const people = [{name: '', age: 0}];

const data = [
  {id: '123', name: 'Bob', lastName: 'Guy', age: 40}, 
  {id: '321', name: 'Michael', lastName: 'Park', age: 20}, 
]

const result = data.map(person => ({
  name: person.name,
  age: person.age,
}));

console.log(result);

You can also keep the desired keys and by using the functions Array.prototype.map and Array.prototype.reduce you can build the expected result:

const model = ["name", "age"];
const data = [
  {id: '123', name: 'Bob', lastName: 'Guy', age: 40}, 
  {id: '321', name: 'Michael', lastName: 'Park', age: 20}, 
]

const result = data.map(person => model.reduce((r, m) => ({...r, [m]: person[m]}), {}), []);

console.log(result);

CodePudding user response:

Just in case you need to implement different person models, you can dinamically create the objects like this

peopleModel = [{ name: "", age: 0 }];

data = [
  { id: "123", name: "Bob", lastName: "Guy", age: 40 },
  { id: "321", name: "Michael", lastName: "Park", age: 20 },
];

const keysArr = Object.keys(peopleModel[0]);
const totalKeys = keysArr.length;

const people = data.reduce((acc, personObj) => {
  const obj = {};
  keysArr.forEach((key) => {
    if (personObj[key]) {
      obj[key] = personObj[key];
    }
  });
  acc.push(obj);
  return acc;
}, []);

console.log(people);

/* logs [
  {name: 'Bob', age: 40}, 
  {name: 'Michael', age: 20}
];
*/

but if you need a different model like

peopleModel = [{ name: "", age: 0, lastName: "" }]

you will get for the log the following:

[
      {name: 'Bob', age: 40, lastName: 'Guy'}, 
      {name: 'Michael', age: 20, lastName: 'Park'}
    ];

that way you do not need to hardcode the keys

  • Related