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

How to get the value from an array and assign to object of arrays?

I am trying to get the values from an array and assign to an array of objects as a new property.
The array of objects:

const employees = [
  {
    firstName: "Ana",
    lastName: "Rosy"
  },
  {
    firstName: "Zion",
    lastName: "Albert"
  },
  {
    firstName: "John",
    lastName: "Doe"
  }
];

An array

const ages = [30, 60, 45]

Desired result

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

const employees = [
  {
    firstName: "Ana",
    lastName: "Rosy",
    age:30
  },
  {
    firstName: "Zion",
    lastName: "Albert",
    age:60
  },
  {
    firstName: "John",
    lastName: "Doe",
    age:45
  }
];

I tried something like this

const employeesWithAge = (ages) => {
  return employees.map((row) => {
    return {
      ...row,
      age: ages
    };
  });
};
const result = employeesWithAge(ages);
console.log("result", result);

But it adds the entire array of ages to the employees array of objects.
Any help will be appreciated

>Solution :

You can use Array.prototype.map() for this. Use the spread syntax (...) on the current element to copy the properties into a new object, then add the age property based on the ages array, using .map() callback’s second parameter (the current index).

employees.map((employee, i) => ({...employee, age: ages[i]}));

Live example:

const employees = [{
    firstName: "Ana",
    lastName: "Rosy"
  },
  {
    firstName: "Zion",
    lastName: "Albert"
  },
  {
    firstName: "John",
    lastName: "Doe"
  }
];

const ages = [30, 60, 45];

const result = employees.map((employee, i) => ({ ...employee, age: ages[i] }));

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