0

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?

1
  • What are the rules for the duplication and what did you try? Commented Nov 9, 2020 at 14:02

2 Answers 2

2

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

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

Comments

0
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 }))

Comments

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.