猿问

操作 javascript 对象数组以获得一组新的对象数组

我有这个对象数组


const unitsAndRates = [

  {

    propertyUnitType: "store",

    propertyUnitRate: "20000",

    numberOfUnit: 4

  },

  {

    propertyUnitType: "duplex",

    propertyUnitRate: "20000",

    numberOfUnit: 3

  }

];


我需要像上面生成的数组这样的东西。


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"

  }

];

考虑到 ,我怎样才能生成上面的输出numberOfUnit?


素胚勾勒不出你
浏览 142回答 2
2回答

慕后森

这可以使用 来完成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);

红颜莎娜

unitsAndRates.map(item => ({  propertyUnitType: item.propertyUnitType,  propertyUnitRate: item.propertyUnitRate}))或者unitsAndRates.map({propertyUnitType, propertyUnitRate} => ({propertyUnitType, propertyUnitRate }))如果您需要按提交的numberOfUnit进行过滤,请尝试:const filteredUnits = unitsAndRates.filter(item => item.numberOfUnit === "2000") 然后你可以做映射filteredUnits.map({propertyUnitType, propertyUnitRate} => ({propertyUnitType, propertyUnitRate }))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答