【问题标题】:Split an array-object without replication在不复制的情况下拆分数组对象
【发布时间】: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


    【解决方案1】:

    给你,对最后一个稍作修改。只是地图名称。

    const arr = [{
      names: ["test1", "test2"],
      values: ["t1", "t2"]
    },
    {
      names: ["test3", "test4"],
      values: ["t3", "t4"]
    }];
    
    const flat = arr.reduce((a, {names, values}) => {
       names.map((name, i) => {   
         a.push({ name, value: values[i]});
      });
      return a;
    }, []).flat();
    
    console.log(`Flat: ${JSON.stringify(flat)}`);

    【讨论】:

    • 好的,抱歉,您想要的输出令人困惑。
    • 谢谢,但问题是这段代码给出了与我相同的输出,而我正在寻找最后一个代码框中的输出
    • 更正以反映您想要的内容。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果你想学习编程,魔法可能不是最好的选择。 map()reduce() 等都是算法本身。基础是使用简单的循环(forwhile)完成这些任务,有时还使用递归(就像这个问题起源的一般解决方案)。

      您目前拥有的是一个数组,您可以在 outer 循环中对其进行迭代,并且其中有具有并行数组的对象,您也可以在 inner 循环中对其进行迭代:

      const array=[ 
          { names:['something1', 'something2'],
            state:false,
            features:['feature1','feature2']
          },
          { names:['something3', 'something4'],
            state:true,
            features:['feature3','feature4']
          },
        ];
        
      for(let outer=0;outer<array.length;outer++){
        let obj=array[outer];
        for(let inner=0;inner<obj.names.length;inner++)
          console.log({
            name:obj.names[inner],
            state:obj.state,
            feature:obj.features[inner]
          });
      }

      那么是的,外部循环根本不需要索引,所以它可以直接遍历元素(for(let obj of array)array.forEach()),但是对于inner 循环,您需要索引,所以它是扔掉它并不是那么简单(请参阅建议的map() 变体的奇怪不平衡:它们有namefeatures[i] - 当然name 实际上已经提取了names[i],但它隐藏了一点两个数组并行遍历的事实)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-22
        • 2018-01-12
        • 1970-01-01
        • 2015-08-31
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 2012-07-09
        相关资源
        最近更新 更多