首页 > 解决方案 > 在不复制的情况下拆分数组对象

问题描述

我正在学习如何处理 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' }

我是编码新手,如果我的话在描述这个问题时不正确,我很抱歉。谢谢你的耐心

标签: javascriptarraysarray.prototype.map

解决方案


您可以使用.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);


推荐阅读