【发布时间】:2023-04-08 08:43:01
【问题描述】:
我正在学习如何处理 js 数组,我想知道是否可以通过拆分现有对象的属性来创建新的数组对象。
我尝试使用 .map 和 .flatMap 来做到这一点,但输出为我提供了复制其他值的对象组合,而我正在寻找独特的对象
我觉得代码可以更清晰一些:
const array=[
{ names:['something1', 'something2'],
state:false,
features:['feature1','feature2']
},
{ names:['something3', 'something4'],
state:true,
features:['feature3','feature4']
},
]
array.flatMap(({names,state,features}) => {
names.flatMap(name => {
features.flatMap(feature => {
console.log(({name,state,feature}));
})
})
})
所以,这段代码的输出是:
{ name: 'something1', state: false, feature: 'feature1' }
{ name: 'something1', state: false, feature: 'feature2' }
{ name: 'something2', state: false, feature: 'feature1' }
{ name: 'something2', state: false, feature: 'feature2' }
{ name: 'something3', state: true, feature: 'feature3' }
{ name: 'something3', state: true, feature: 'feature4' }
{ name: 'something4', state: true, feature: 'feature3' }
{ name: 'something4', state: true, feature: 'feature4' }
但我希望输出是:
{ name: 'something1', state: false, feature: 'feature1' },
{ name: 'something2', state: false, feature: 'feature2' },
{ name: 'something3', state: true, feature: 'feature3' },
{ name: 'something4', state: true, feature: 'feature4' }
我是编码新手,如果我在描述这个问题时用词不正确,请见谅。 感谢您的耐心等待
【问题讨论】:
标签: javascript arrays array.prototype.map