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...

1
  • 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. Commented Mar 13, 2021 at 6:38

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.