map an array inside object of an array

Viewed 364

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

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

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

Maybe:

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

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

Related