Home > front end >  Make a new list of objects with added properties
Make a new list of objects with added properties

Time:10-12

I have the following two arrays for example:

Employees = [
  { id: 1, name: Ahmed, age: 22 },
  { id: 2, name: hassan, age: 43 },
  { id: 3, name: john, age: 44 },
  { id: 4, name: salem, age: 66 }
]

b = [{ emp_id: 1, name: Ahmed }, { emp_id: 4, name: salem }]

Now I want a new array that is same as employees but a new property added which isSelected. If the emp_id in array b exists in employees array add a property isSelected : true else false For example:

MyNewList = [
  { id: 1, name: Ahmed, age: 22, isSelected: true },
  { id: 2, name: hassan, age: 43, isSelected: false },
  { id: 3, name: john, age: 44, isSelected: false },
  { id: 4, name: salem, age: 66, isSelected: true }
]

CodePudding user response:

You can simply map() over the first array and assign isSelected by checking if some() of the elements in b match the currently iterated object's id.

const employees = [
  { id: 1, name: 'Ahmed', age: 22 },
  { id: 2, name: 'hassan', age: 43 },
  { id: 3, name: 'john', age: 44 },
  { id: 4, name: 'salem', age: 66 }
];

const b = [{ emp_id: 1, name: 'Ahmed' }, { emp_id: 4, name: 'salem' }];

const newList = employees.map((e) => (
  {
    ...e,
    isSelected: b.some(({ emp_id }) => emp_id === e.id)
  }
));


console.log(newList);

Alternatively you could create a Set of emp_ids from b and assign isSelected by checking if the Set.has() the currently iterated id.

const employees = [{ id: 1, name: 'Ahmed', age: 22 }, { id: 2, name: 'hassan', age: 43 }, { id: 3, name: 'john', age: 44 }, { id: 4, name: 'salem', age: 66 }];
const b = [{ emp_id: 1, name: 'Ahmed' }, { emp_id: 4, name: 'salem' }];

const empIds = new Set(b.map(({ emp_id }) => emp_id));
const newList = employees.map((e) => (
  {
    ...e,
    isSelected: empIds.has(e.id)
  }
));


console.log(newList);

see also:

CodePudding user response:

I would encourage you to look into documentation for object spread as well as array methods such as find, map, and filter. You'll encounter those a lot in the future.

To answer the question, something like this would probably work:

MyNewList = Employees.map((employee) => ({
    ...employee,
    isSelected: b.find((selectedEmployee) => selectedEmployee.emp_id === employee.id) !== undefined,
}))

Explanation: The ...employee is object spread. You'll use this a lot I suggest you look into it. It puts all the properties of the original object into the new one. Then we add a new isSelected property, and we use b.find to see if this employee has an id in list b. We use !== undefined because if the find is undefined, the employee is NOT in the list.

CodePudding user response:

same as pilchard's answer with a if - else

  • Related