gpt4 book ai didi

javascript - 为每个对象创建唯一 ID

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:09:06 25 4
gpt4 key购买 nike

概述:有一个产品组对象数组,每个产品组都有一个项目数组。具有唯一 ID 的产品组对象,但项目数组未分配任何唯一 ID。请在下方找到 JSON 对象。

const productList = [{
productGroup : 'PG1',
index: 1,
items: [{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
}]
}, {
productGroup : 'PG2',
index: 2,
items: [{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
}]
}];

要求:根据产品组为 items 数组的每个项目对象分配一些唯一的 ID。

到目前为止我试过了: working solution : concat index of product group with the index of each list items

const productList = [{
productGroup : 'PG1',
index: 1,
items: [{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
}]
}, {
productGroup : 'PG2',
index: 2,
items: [{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
}]
}];

const itemList = productList.map(obj => {
obj.items.map((itemObj, index) => {
itemObj.productGroup = obj.productGroup;
itemObj.pgIndex = obj.index;
itemObj.itemIndex = obj.index + '' + index;
});
return obj.items;
});

var mergedListItems = itemList.reduce((arr, arrNext) => arr.concat(arrNext));

console.log('mergedListItems', mergedListItems);

这种方法好吗?如果否,那么你能帮我找到最好的方法吗?

最佳答案

您可能会立即将 .reduce 放入输出数组,而不是多次迭代这些项目:

const productList = [{
productGroup : 'PG1',
index: 1,
items: [{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
}]
}, {
productGroup : 'PG2',
index: 2,
items: [{
item1: 'item1 value',
item2: 'item2 value'
},{
item1: 'item1 value',
item2: 'item2 value'
}]
}];

const mergedListItems = productList.reduce((a, { productGroup, index, items }) => {
items.forEach((itemObj, itemIndex) => {
a.push({
...itemObj,
productGroup,
pgIndex: index,
itemIndex: `${index}${itemIndex}`
});
});
return a;
}, []);
console.log(mergedListItems);

另请注意,您的

可能存在问题
itemObj.itemIndex = obj.index + '' + index;

逻辑 - 如果 index 大于 10 怎么办?然后,您可能会看到 itemIndex111 的项目。这是什么意思,是说原始对象的索引是 11,还是项目索引是 11?如果可能,考虑在它们之间加上下划线或一些分隔符,例如

itemObj.itemIndex = obj.index + '_' + index;

或者,像我的代码一样使用模板文字

itemIndex: `${index}_${itemIndex}`

关于javascript - 为每个对象创建唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com