javascript - 通过拆分属性为数组的对象来创建对象
问题描述
我有一个对象数组,其属性是数组(可变长度),我想用通过组合数组属性中存在的元素创建的新对象(在同一个数组中)替换这些对象。我正在使用 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
},
...
]
解决方案
使用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}));
})
})
})
推荐阅读
- pandas - 使用“df.groupby(column).apply()”时,在“应用”上下文中获取 groupby 列?
- java - java.lang.NoSuchMethodException 使用 Pagefactory 对象运行 Appium Java 类时出错
- javascript - 如何在后端验证来自前端的输入 - MERN
- php - 如何为字符串base64 blob不可读创建链接
- python - 在 Pandas 中加入字符串列并删除重复项和其他列
- sqlite - 如何在 Peewee 和 SQLite 的 FTS5 中使用 trigram tokenizer/similarity 选项?
- c++ - 无法显示图像opencv(c ++)
- authentication - JWT 注册问题
- javascript - db.collection 不是函数 firebase firestore
- python - 为什么一个简单的网页抓取代码在 pycharm 上运行缓慢但在 google colab 上运行得很快?