Chibuike Patrick
Chibuike Patrick

Reputation: 13

Manipulating javascript array of objects to obtain a new set of array of objects

I have this array of objects

const unitsAndRates = [
  {
    propertyUnitType: "store",
    propertyUnitRate: "20000",
    numberOfUnit: 4
  },
  {
    propertyUnitType: "duplex",
    propertyUnitRate: "20000",
    numberOfUnit: 3
  }
];

and I need something like this generated array from the one above.

const generated = [
  {
    propertyUnitType: "store1",
    propertyUnitRate: "20000"
  },
  {
    propertyUnitType: "store2",
    propertyUnitRate: "20000"
  },
  {
    propertyUnitType: "store3",
    propertyUnitRate: "20000"
  },
  {
    propertyUnitType: "store4",
    propertyUnitRate: "20000"
  },
  {
    propertyUnitType: "duplex1",
    propertyUnitRate: "20000"
  },
  {
    propertyUnitType: "duplex2",
    propertyUnitRate: "20000"
  },
  {
    propertyUnitType: "duplex3",
    propertyUnitRate: "20000"
  }
];

How can I generate the output above considering the numberOfUnit?

Upvotes: 0

Views: 47

Answers (2)

user3753974
user3753974

Reputation: 71

unitsAndRates.map(item => ({
  propertyUnitType: item.propertyUnitType,
  propertyUnitRate: item.propertyUnitRate
}))

or

unitsAndRates.map({propertyUnitType, propertyUnitRate} => ({propertyUnitType, propertyUnitRate }))

And if you need to filter by numberOfUnit filed try:

const filteredUnits = unitsAndRates.filter(item => item.numberOfUnit === "2000") 

and then you can do mapping

filteredUnits.map({propertyUnitType, propertyUnitRate} => ({propertyUnitType, propertyUnitRate }))

Upvotes: 0

Derek Wang
Derek Wang

Reputation: 10194

This can be done using Array.prototype.flatMap.

const unitsAndRates = [
  {
    propertyUnitType: "store",
    propertyUnitRate: "20000",
    numberOfUnit: 4
  },
  {
    propertyUnitType: "duplex",
    propertyUnitRate: "20000",
    numberOfUnit: 3
  }
];

const result = unitsAndRates.flatMap((item) => [...Array(item.numberOfUnit).keys()].map((index) => ({
  propertyUnitType: item.propertyUnitType + (index + 1),
  propertyUnitRate: item.propertyUnitRate
})));
console.log(result);

Upvotes: 2

Related Questions