首页 > 解决方案 > 通过拆分属性为数组的对象来创建对象

问题描述

我有一个对象数组,其属性是数组(可变长度),我想用通过组合数组属性中存在的元素创建的新对象(在同一个数组中)替换这些对象。我正在使用 js 类的函数,这就是为什么你会看到“this”。人们建议我使用 .reduce() 和 .map(),但我不知道如何使用它们。这是目标:


    this.apple="apple"

    this.Array=[ 
      { names:[something1, something2...]
        fruit:this.apple
        features:[feature1,feature2,...]
      }
    ]

预期的输出将是:

      // (expected output):

    this.Array=[
      { names:something1,
        fruit:this.apple
        features:feature1
      },
      { names:something1,
        fruit:this.apple
        features:feature2
      },
      { names:something2,
        fruit:this.apple
        features:feature1
      },
      { names:something2,
        fruit:this.apple
        features:feature2
      },
      ...
    ]

标签: javascriptarrays

解决方案


使用flatMap您可以取消组合数组中的元素..

const fruit = 'apple'

const array=[ 
  { names:['something1', 'something2'],
    fruit: fruit,
    features:['feature1','feature2']
  }
]

array.flatMap(({names,fruit,features}) => {
  names.flatMap(name => {
    features.flatMap(feature => {
      console.log(({name,fruit,feature}));
    })
  })
})


推荐阅读