Skip to content
Advertisement

Push multiple objects to an already initialized, empty object array

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!

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement