2

So I have an array of objects with many, keys, something like that:

[
 { id: 1,
   phoneNumber: 12345,
   name: "John",
   underLicense: true
 },
 { id: 2,
   phoneNumber: 12345,
   name: "Jane",
   underLicense: false
 }
]

The way i want it to look like is this:

[
 { listPhone: [
    { number: 12345,
      underLicense: true
    },
    { number: 12345
      underLicense: false
    }
  ]
 }
]

so for that, first i do the map(), and then I push it into listPhones

here is my function

  saveLicense() {
    const listPhone = this.toSend.map(x => {
      return {
          number: x.phoneNumber,
          underLicense: x.underLicense
        };
    });
    const savedPhones = [];
    savedPhones.push({listPhone: listPhone});
  }

The question is, is there a way to to it in the map() metod, without having to use push in the second step

3 Answers 3

3

You could directly map to an expression for a property value.

saveLicense() {
    const
        savedPhones = [{ listPhone: this.toSend.map(({ phoneNumber: number, underLicense }) =>
            ({ number, underLicense })
        ) }];
}
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe:

saveLicense () {
  const listPhone = this.toSend.map((x) => ({
    number: x.phoneNumber,
    underLicense: x.underLicense,
  }));
  const savedPhones = [{ listPhone }];
};

1 Comment

this one works just fine, but i wanted it to be in the map only, so the answer below is marked as the best one
0

saveLicense() {
    const listPhone = this.toSend.map(x => {
      return { listPhone: {
          number: x.phoneNumber,
          underLicense: x.underLicense
          }
        };
    });
 return [listPhone]
  }

2 Comments

tried that, but this one makes it look like this: {listPhone:{number, underLicense}},{listPhone: {number, underLicense}}
return [listPhone]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.