How can I filter the rooms array with elements in the object and if it matches to object id in the array of objects with item type "Room" add count key with count to the main array?
The First Array that I get from API
[
{
rooms: [ 'f03e6e40-870d-11eb-88a2-0149a30c02c5' ],
itemType: 'Item',
id: '8c6a6070-80c0-11eb-9753-bb149505e85f',
itemName: 'Item 1’,
},
{
rooms: [ 'eef60fc0-870d-11eb-88a2-0149a30c02c5' ],
itemType: 'Item',
id: '3aede320-870f-11eb-9e58-9d6fb0d8b5a8',
itemName: 'Item 2'
},
{
rooms: [ 'f03e6e40-870d-11eb-88a2-0149a30c02c5' ],
itemType: 'Item',
id: '3ad52b00-870f-11eb-8f84-0782ebd81006',
itemName: ‘Item3’
},
{
itemType: 'Room',
id: 'f03e6e40-870d-11eb-88a2-0149a30c02c5',
itemName: 'Bedroom’
},
{
itemType: 'Room',
id: 'eef60fc0-870d-11eb-88a2-0149a30c02c5',
itemName: 'Bedroom 2'
},
]
I want to filter the rooms array with elements in the object and if it matches to object id in the array of objects with itemtType "Room" add count key with count to main array as below.
[
{
rooms: [ 'f03e6e40-870d-11eb-88a2-0149a30c02c5' ],
itemType: 'Item',
id: '8c6a6070-80c0-11eb-9753-bb149505e85f',
itemName: 'Item 1’,
},
{
rooms: [ 'eef60fc0-870d-11eb-88a2-0149a30c02c5' ],
itemType: 'Item',
id: '3aede320-870f-11eb-9e58-9d6fb0d8b5a8',
itemName: 'Item 2'
},
{
rooms: [ 'f03e6e40-870d-11eb-88a2-0149a30c02c5' ],
itemType: 'Item',
id: '3ad52b00-870f-11eb-8f84-0782ebd81006',
itemName: ‘Item3’
},
{
itemType: 'Room',
id: 'f03e6e40-870d-11eb-88a2-0149a30c02c5',
itemName: 'Bedroom’,
count: 2
},
{
itemType: 'Room',
id: 'eef60fc0-870d-11eb-88a2-0149a30c02c5',
itemName: 'Bedroom 2',
count: 1
},
]
You can use Array.prototype.map
to transform the input array and add the count
property to the elements with an itemType
of 'Room'
. You can use Array.prototype.filter
and Array.prototype.includes
to count the number of rooms.
const arr = [ { rooms: ['f03e6e40-870d-11eb-88a2-0149a30c02c5'], itemType: 'Item', id: '8c6a6070-80c0-11eb-9753-bb149505e85f', itemName: 'Item 1', }, { rooms: ['eef60fc0-870d-11eb-88a2-0149a30c02c5'], itemType: 'Item', id: '3aede320-870f-11eb-9e58-9d6fb0d8b5a8', itemName: 'Item 2', }, { rooms: ['f03e6e40-870d-11eb-88a2-0149a30c02c5'], itemType: 'Item', id: '3ad52b00-870f-11eb-8f84-0782ebd81006', itemName: 'Item3', }, { itemType: 'Room', id: 'f03e6e40-870d-11eb-88a2-0149a30c02c5', itemName: 'Bedroom', }, { itemType: 'Room', id: 'eef60fc0-870d-11eb-88a2-0149a30c02c5', itemName: 'Bedroom 2', }, ] const result = arr.map((element) => { if (element.itemType.== 'Room') { return element } return {..,element: count. arr.filter( (i) => i.itemType === 'Item' && i.rooms.includes(element.id) ),length. } }) console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.