gpt4 book ai didi

javascript - 使用两个数组特定数据和值创建新数组

转载 作者:行者123 更新时间:2023-12-04 01:14:41 25 4
gpt4 key购买 nike

我想使用两个数组创建一个新数组。

itemsAll = [
{id: 1, itemId: 1, serialNo:"11111111", itemTypeId: 1, itemMasterId: 1, itemStatus: 0, updatedBy: 1 },
{id: 2, itemId: 2, serialNo:"2222222", itemTypeId: 3, itemMasterId: 2, itemStatus: 0, updatedBy: 1 }
];

有一个 itemTypeId,我想获得与 itemTypeId 匹配的 itemTypeName。

itemType = [
{id: 3, itemTypeId: 1, itemTypeName: "type Name 1", description: "Hello", itemTypeStatus: 0, status: true },
{id: 13, itemTypeId: 2, itemTypeName: "type Name 2", description: "222 Hello", itemTypeStatus: 0, status: true },
{id: 15 , itemTypeId: 3, itemTypeName: "type Name 3", description: "333 Hello", itemTypeStatus: 0, status: true }
];

预期数组

itemsAllNew = [
{id: 1, itemId: 1, serialNo:"11111111", itemTypeId: 1, itemTypeName: "type Name 1", itemMasterId: 1, itemStatus: 0, updatedBy: 1 },
{id: 2, itemId: 2, serialNo:"2222222", itemTypeId: 3, , itemTypeName: "type Name 3", itemMasterId: 2, itemStatus: 0, updatedBy: 1 }
];

我在下面添加了尝试过的解决方案,但它也包含不需要的键值对。

const output = itemsAll.map(
itemsall => Object.assign(itemsall, itemType.find((itemtype) => itemtype.itemTypeId === itemsall.itemTypeId))
);

console.log(output);

附上输出截图。

enter image description here

最佳答案

您可以创建一个 Map对象并用时间复杂度 O(1) 映射它:

const mapItemType = new Map(itemType.map(i => [i.itemTypeId, i.itemTypeName]));
const result = itemsAll.map(({itemTypeId, ...other}) =>
({itemTypeName: mapItemType.get(itemTypeId), ...other }))

一个例子:

let itemsAll = [
{id: 1, itemId: 1, serialNo:"11111111", itemTypeId: 1, itemMasterId: 1, itemStatus: 0, updatedBy: 1 },
{id: 2, itemId: 2, serialNo:"2222222", itemTypeId: 3, itemMasterId: 2, itemStatus: 0, updatedBy: 1 }
];

let itemType = [
{id: 3, itemTypeId: 1, itemTypeName: "type Name 1", description: "Hello", itemTypeStatus: 0, status: true },
{id: 13, itemTypeId: 2, itemTypeName: "type Name 2", description: "222 Hello", itemTypeStatus: 0, status: true },
{id: 15 , itemTypeId: 3, itemTypeName: "type Name 3", description: "333 Hello", itemTypeStatus: 0, status: true }
];

const mapItemType = new Map(itemType.map(i => [i.itemTypeId, i.itemTypeName]));
const result = itemsAll.map(({itemTypeId, ...other}) => ({itemTypeName: mapItemType.get(itemTypeId), ...other }))
console.log(result)

关于javascript - 使用两个数组特定数据和值创建新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63754225/

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