【发布时间】:2019-06-19 20:41:50
【问题描述】:
我想将嵌套数组、对象更改为另一个结构,所以我发布了一个问题。
// 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。
我想自己解决,但我没有足够的能力解决它。非常感谢您的帮助。
我有一个问题。是不是比for循环使用reduce、map等数组方法求解更简单?
感谢阅读。
【问题讨论】:
标签: javascript arrays object nested structure