Reputation: 13
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
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
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