Create new Array using two Arrays Specific data and values

Tags: ,



I want to create a new Array using two arrays.

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 }
];

There is a itemTypeId i want to get itemTypeName match with itemTypeId.

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 }
];

Expected Array

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 }
];

I added below tried solution but its contain unwanted key-value pairs also.

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

console.log(output);

Attached screenshot of output.

enter image description here

Answer

You can create a Map object and map it with time complexity O(1):

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

An example:

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)


Source: stackoverflow