I want to create a new Array using two arrays.
JavaScript
x
5
1
itemsAll = [
2
{id: 1, itemId: 1, serialNo:"11111111", itemTypeId: 1, itemMasterId: 1, itemStatus: 0, updatedBy: 1 },
3
{id: 2, itemId: 2, serialNo:"2222222", itemTypeId: 3, itemMasterId: 2, itemStatus: 0, updatedBy: 1 }
4
];
5
There is a itemTypeId i want to get itemTypeName match with itemTypeId.
JavaScript
1
6
1
itemType = [
2
{id: 3, itemTypeId: 1, itemTypeName: "type Name 1", description: "Hello", itemTypeStatus: 0, status: true },
3
{id: 13, itemTypeId: 2, itemTypeName: "type Name 2", description: "222 Hello", itemTypeStatus: 0, status: true },
4
{id: 15 , itemTypeId: 3, itemTypeName: "type Name 3", description: "333 Hello", itemTypeStatus: 0, status: true }
5
];
6
Expected Array
JavaScript
1
5
1
itemsAllNew = [
2
{id: 1, itemId: 1, serialNo:"11111111", itemTypeId: 1, itemTypeName: "type Name 1", itemMasterId: 1, itemStatus: 0, updatedBy: 1 },
3
{id: 2, itemId: 2, serialNo:"2222222", itemTypeId: 3, , itemTypeName: "type Name 3", itemMasterId: 2, itemStatus: 0, updatedBy: 1 }
4
];
5
I added below tried solution but its contain unwanted key-value pairs also.
JavaScript
1
6
1
const output = itemsAll.map(
2
itemsall => Object.assign(itemsall, itemType.find((itemtype) => itemtype.itemTypeId === itemsall.itemTypeId))
3
);
4
5
console.log(output);
6
Attached screenshot of output.
Advertisement
Answer
You can create a Map object and map it with time complexity O(1)
:
JavaScript
1
4
1
const mapItemType = new Map(itemType.map(i => [i.itemTypeId, i.itemTypeName]));
2
const result = itemsAll.map(({itemTypeId, other}) =>
3
({itemTypeName: mapItemType.get(itemTypeId), other }))
4
An example:
JavaScript
1
14
14
1
let itemsAll = [
2
{id: 1, itemId: 1, serialNo:"11111111", itemTypeId: 1, itemMasterId: 1, itemStatus: 0, updatedBy: 1 },
3
{id: 2, itemId: 2, serialNo:"2222222", itemTypeId: 3, itemMasterId: 2, itemStatus: 0, updatedBy: 1 }
4
];
5
6
let itemType = [
7
{id: 3, itemTypeId: 1, itemTypeName: "type Name 1", description: "Hello", itemTypeStatus: 0, status: true },
8
{id: 13, itemTypeId: 2, itemTypeName: "type Name 2", description: "222 Hello", itemTypeStatus: 0, status: true },
9
{id: 15 , itemTypeId: 3, itemTypeName: "type Name 3", description: "333 Hello", itemTypeStatus: 0, status: true }
10
];
11
12
const mapItemType = new Map(itemType.map(i => [i.itemTypeId, i.itemTypeName]));
13
const result = itemsAll.map(({itemTypeId, other}) => ({itemTypeName: mapItemType.get(itemTypeId), other }))
14
console.log(result)