1

Let’s consider the next array:

const arr = [
 {
   name: "bob",
   age: 25,
   salary: 1000
 },
 {
   name: "bill",
   age: 32,
   salary: 1500
 },
 {
   name: "jake",
   age: 16,
   salary: null
 },
]

I need to map every object to be the next structure:

firstName: string;
personAge: string;
grossSalary?: number;

so

const mappedArr = arr.map(person => ({
 firstName: person.name,
 personAge: person.age,
 ...{grossSalary:
   person.salary
   ? person.salary
   : // I'm stuck :'((
   }
}))

I need to map person.salary only if it’s not null in the original object. Otherwise, I need to omit it.

I believe I’m pretty close with the spread operator but I guess I need a ternary to return an empty object if the salary is null in the original object. Maybe this approach is wrong... idk anymore...

anotheruser
  • 582
  • 1
  • 7
  • 23
  • It would need to be something like `...{person.salary === undefined ? {} : {grossSalary: person.salary}}`, so if it's undefined, you spread an empty object, adding no keys to the parent object, otherwise, you spread an object with `grossSalary`, adding it as a key to the parent object. – Nick Parsons Mar 13 '21 at 06:38

1 Answers1

2

You can check the salary based on which you can return the object:

const arr = [
 {
   name: "bob",
   age: 25,
   salary: 1000
 },
 {
   name: "bill",
   age: 32,
   salary: 1500
 },
 {
   name: "jake",
   age: 16,
   salary: null
 },
]
const mappedArr = arr.map(person => (
    person.salary 
    ? { firstName: person.name, personAge: person.age, grossSalary: person.salary }
    : { firstName: person.name, personAge: person.age }
  )
);
  
console.log(mappedArr);
Mamun
  • 66,969
  • 9
  • 47
  • 59