Javascript:更改嵌套数据结构

时间:2019-06-18 11:30:42

标签: javascript arrays object nested structure

我想将嵌套数组,对象更改为另一种结构,所以我提出了一个问题。

// 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。 我想自己解决它,但是我没有足够的能力解决它。感谢您的帮助。

我有一个问题。是否比使用forreduce这样的数组方法来解决map循环简单?

感谢阅读。

1 个答案:

答案 0 :(得分:0)

您可以(即将使用)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);

相关问题