通过拆分属性为数组的对象来创建对象 [英] Creating objects by splitting an object whose attributes are arrays

查看:62
本文介绍了通过拆分属性为数组的对象来创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,其属性是数组(可变长度),我想将这些对象替换为通过合并数组属性中存在的元素而创建的新对象(在同一数组中)。
我正在使用js类的函数,这就是为什么您看到 this的原因。
人们建议我使用.reduce()和.map(),但我不知道如何使用它们。
这是目标:

I have an array of objects whose attributes are arrays (of variable length) and I want to replace those objects with new ones (in the same array) created by combining the elements present in the array-attributes. I'm working in a function of a js class, that's why you see "this." People suggested me to use .reduce() and .map(), but I didn't figure out how to use them. Here's the goal:


    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 ,您可以取消数组中元素的分组。

Using flatMap you can ungroup the elements in an array..

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}));
    })
  })
})

这篇关于通过拆分属性为数组的对象来创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆