Javascript: 改变嵌套数据结构

Javascript: Changing the nested data structure

我想将一个嵌套数组、对象更改为另一个结构,所以我post一个问题。

// before
const beforeData = [
  { 
    product_id: 1,
    attribute_values: [
      { attribute_value_id: 1 },
      { attribute_value_id: 2 },
      { attribute_value_id: 3 }
    ]
  }, 
  { 
    product_id: 2,
    attribute_values: [
      { attribute_value_id: 1 },
      { attribute_value_id: 2 },
      { attribute_value_id: 3 }
    ]
  },

  (...)
];

// after
const afterData = [
  { product_id: 1, attribute_value_id: 1 },
  { product_id: 1, attribute_value_id: 2 },
  { product_id: 1, attribute_value_id: 3 },
  { product_id: 2, attribute_value_id: 1 },
  { product_id: 2, attribute_value_id: 2 },
  { product_id: 2, attribute_value_id: 3 },
];

我尝试使用库以某种方式创建我想要的数据结构。但是我没有得到我想要的,我得到了 lodash 的帮助。注意attribute_values.length是完全一样的

const getAttributeValueId = _.chain(beforeData[0].attribute_values)
  .flatten()
  .value();

console.log(getAttributeValueId)

在控制台上:

[ { attribute_value_id: 1 },
  { attribute_value_id: 2 },
  { attribute_value_id: 3 } ]
const getProductId = () => {
  const arrOne = [];
  data.forEach((val, idx) => {
    arrOne[idx] = { product_id: val.product_id };
  });

  const arrTwo = [];
  _.forEach(arrOne, (val, idx) => {
    for (let i = 0; i < getAttributeValueId.length; i++) {
      arrTwo.push(arrOne[idx]);
    }
  });
  return arrTwo;
};

console.log(getProductId());

在控制台上:

[ { product_id: 1 },
  { product_id: 1 },
  { product_id: 1 },
  { product_id: 2 },
  { product_id: 2 },
  { product_id: 2 },
  { product_id: 3 },
  { product_id: 3 },
  { product_id: 3 } ]

我不知道如何为每个数组插入 attribute_value_id。 我想自己解决,但我没有足够的能力解决它。非常感谢您的帮助。

我有一个问题。像reduce,map?

这样的数组法求解比用for循环更简单吗

感谢阅读。

您可以采用(即将发布的)Array#flatMap 并将通用 属性 映射到每个嵌套属性。

const
    data = [{ product_id: 1, attribute_values: [{ attribute_value_id: 1 }, { attribute_value_id: 2 }, { attribute_value_id: 3 }] }, { product_id: 2, attribute_values: [{ attribute_value_id: 1 }, { attribute_value_id: 2 }, { attribute_value_id: 3 }] }],
    result = data.flatMap(({ product_id, attribute_values }) =>
        attribute_values.map(o => ({ product_id, ...o })));
    
console.log(result);