javascript - 在不复制的情况下拆分数组对象
问题描述
我正在学习如何处理 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' }
我是编码新手,如果我的话在描述这个问题时不正确,我很抱歉。谢谢你的耐心
解决方案
您可以使用.flatMap()
内部.map()
函数(而不是.flatMap()
像您正在做的那样)将names
数组中的每个元素映射到与其关联的各自的对象feature
。
请参见下面的示例:
const array = [{
names: ['something1', 'something2'],
state: false,
features: ['feature1', 'feature2']
},
{
names: ['something3', 'something4'],
state: true,
features: ['feature3', 'feature4']
},
];
const res = array.flatMap(
({names, state, features}) => names.map((name, i) => ({name, state, feature: features[i]}))
);
console.log(res);
推荐阅读
- python - Tkinter,如何调整树视图缩进大小和指示箭头图像
- wordpress - 在 Google Cloud WordPress HA 上添加 SSL 使 wp-admin 无法访问
- css - 表格中的文本旋转在 Firefox 和 Chrome 上不起作用
- c - C中的行主要顺序作为命令行参数
- python - gensim word2vec 日志文件中 in_qsize 和 out_qsize 的含义
- python - 在 HDF5 数据集中写入 2D Numpy 数组
- c# - 如何为不同的处理器架构同时构建 UWP 应用程序包
- docker - 使用 Gitlab CI 构建和部署?
- django - 是否可以从 MySQL 数据库中提取 600,000 行并将其显示为邮递员中的 JSON 数据?
- c++ - 局部范围内的常量命名空间