【问题标题】:I need to combine all objects from an array element into one new array of objects我需要将数组元素中的所有对象组合成一个新的对象数组
【发布时间】:2021-11-14 07:02:49
【问题描述】:

我有一个嵌套数组,其中包含名为“选项”的属性。 options 属性是一个对象数组,现在每个对象都有自己的属性字段,也是一个对象数组。

因此,我需要从选项数组中的每个选项中获取选项字段,并将它们全部放入一个新数组中。

我将发布我的数组的外观图像,因为它可能更容易理解它的外观。 Here is the array image.

现在我已经尝试通过它们进行映射,然后获取字段,但以我的方式它返回数组但每个字段对象,但我希望它返回,因为字段中的每个字段都应该是一个新的数组属性。

const obj = {
  key: 'clothes',
  label: 'Clothes',
  options: [
    {
      key: 'base-layers',
      label: 'base-layers',
      fields: [{ key: 'brand', label: 'brand' }, { key: 'size', label: 'Size' }],
    },
    {
      key: 'front-layers',
      label: 'front-layers',
      fields: [{ key: 'gender', label: 'Gender' }, { key: 'condition', label: 'Condition' }],
    },
  ],
};

const getFields = obj.options.map(a => a.map(f => f.fields));

const final = getFields.reduce((r, c) => Object.assign(r, c), {}));

因此,fields 对象中的每个字段都应该是新对象数组中的自己的属性。

我真的很感谢您的帮助!

【问题讨论】:

  • 您的预期结果应该是什么?请自行添加代码?

标签: javascript arrays reactjs javascript-objects


【解决方案1】:

您可以使用单个 reduce 函数来迭代每个选项并组合字段集合。

const obj = {
  key: 'clothes',
  label: 'Clothes',
  options: [
    {
      key: 'base-layers',
      label: 'base-layers',
      fields: [{ key: 'brand', label: 'brand' }, { key: 'size', label: 'Size' }, { key: 'condition', label: 'Condition' }],
    },
    {
      key: 'front-layers',
      label: 'front-layers',
      fields: [{ key: 'gender', label: 'Gender' }, { key: 'condition', label: 'Condition' }],
    },
  ],
};

const allFields = obj.options.reduce((fields, option) => [...fields, ...option.fields], []);

console.log(allFields);


// Combine all fields without duplications (not optimized)

const allFieldsUnique = obj.options.reduce((fields, option) => {
  return [...fields, ...option.fields.filter(a => !fields.some(b => b.key === a.key))];
}, []);

console.log(allFieldsUnique);

【讨论】:

  • 我会将此标记为答案,就像一个魅力!谢谢!你能帮我看看如何让这个新数组只有唯一的对象,所以如果里面有两个带有关键“品牌”的项目,我怎么能只保留一个等等?
  • 不错!我添加了第二个过滤掉重复字段的示例。
  • 非常感谢克里斯!
【解决方案2】:

使用Array.flatMap() 通过从每个选项中提取字段来获取一个数组。

如果您想要一个对象,请将字段映射到 [key, value] 对的数组,然后转换为带有 Object.fromEntries() 的对象:

const obj = {"key":"clothes","label":"Clothes","options":[{"key":"base-layers","label":"base-layers","fields":[{"key":"brand","label":"Brand"},{"key":"size","label":"Size"}]},{"key":"front-layers","label":"front-layers","fields":[{"key":"gender","label":"Gender"},{"key":"condition","label":"Condition"}]}]};

const arr = obj.options.flatMap(option => option.fields)

console.log(arr);

const object = Object.fromEntries(obj.options.flatMap(option =>
  option.fields.map(({ key, label }) => [key, label])
));

console.log(object);

【讨论】:

  • 感谢您的帮助,您的解决方案似乎非常好,即使我先选择了上面的解决方案。再次感谢!!
  • 没有独特的过滤器,我想我更喜欢flatMap,因为它比reduce短得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
  • 2022-01-04
  • 2012-09-14
  • 1970-01-01
相关资源
最近更新 更多