How to loop inside a map() loop? - javascript

The below script outputs
================================================
Log entry ID: 1
UUID: 2
Timestamp: 3
--------------------
Log entry ID: 4
UUID: 5
Timestamp: 6
which is what I want.
Right now description is hard coded, where I would like it to be built using arr instead.
My current thinking were to somehow generate the inner array in the map() function:
[
`Log entry ID: ${element['_id']}`,
`UUID: ${element['_source'].uuid}`,
`Timestamp: ${element['_source']['#timestamp']}\n`,
]
but because of the templating, this is not even a valid array with 3 elements, when looking at it on its own. So I am all out of ideas.
Question
Somehow I have to loop over the elements in arr before it is given to map(), I suppose.
Does anyone know how that could be done?
const dedent = require('dedent');
const arr = [
[ 'Log entry ID', '_id' ],
[ 'UUID', 'uuid' ],
[ 'Timestamp', '#timestamp' ],
]
;
const docs = [
{'_id': 1,'_source': {'uuid': 2,'#timestamp': 3}},
{'_id': 4,'_source': {'uuid': 5,'#timestamp': 6}},
];
const description = dedent`
================================================
${
docs.map((element) => [
`Log entry ID: ${element['_id']}`,
`UUID: ${element['_source'].uuid}`,
`Timestamp: ${element['_source']['#timestamp']}\n`,
].join('\n')).join('--------------------\n')
}
`;
console.log(description);
Update
I control arr so changing it to eg. is possible, or something else
const arr = [
[ 'Log entry ID', '_id' ],
[ 'UUID', {'_source': 'uuid'} ],
[ 'Timestamp', {'_source': '#timestamp'} ],
]
;

Since arr is in your control perhaps you can specify the path of the key itself.
const arr = [
['Log entry ID', '_id'],
['UUID', '_source.uuid'],
['Timestamp', '_source.#timestamp'],
['Description', '_source._desc']
];
const docs = [{
'_id': 1,
'_source': {
'uuid': 2,
'#timestamp': 3,
'_desc': 'test 1'
}
},
{
'_id': 4,
'_source': {
'uuid': 5,
'#timestamp': 6,
'_desc': 'test 2'
}
},
];
const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);
console.log(docs.map((element) => arr.map((label) => {
return `${label[0]}: ${getValue(element, label[1])}`
}).join('\n')).join('\n--------------------\n'))

Assuming that the keys of a docs array element are all unique, one could traverse the object looking for a matching key.
function findVal(object, key) {
var value;
Object.keys(object).some(function(k) {
if (k === key) {
value = object[k];
return true;
}
if (object[k] && typeof object[k] === 'object') {
value = findVal(object[k], key);
return value !== undefined;
}
});
return value;
}
docs.map((element) =>
arr.map(([item, key]) =>
`${item}: ${findVal(element, key)}`)
)
The FindVal is taken from here.

you could create a function to get data from arr and put in description
/* Simple Hello World in Node.js */
const arr = [
[ 'Log entry ID', '_id' ],
[ 'UUID', 'uuid' ],
[ 'Timestamp', '#timestamp' ],
]
;
const docs = [
{'_id': 1,'_source': {'uuid': 2,'#timestamp': 3}},
{'_id': 4,'_source': {'uuid': 5,'#timestamp': 6}},
];
const findInArr=function(value){
var t = ""
arr.forEach(item=>{
if (item.includes(value)) {t = item[0]}
})
return t
}
const description = dedent`
================================================
${
docs.map((element) => [
`${findInArr('_id')}: ${element['_id']}`,
`${findInArr('UUID')}: ${element['_source'].uuid}`,
`${findInArr('Timestamp')}: ${element['_source']['#timestamp']}\n`,
].join('\n')).join('--------------------\n')
}`;
console.log(description);

Related

Merging contents of an array based on matching content

I am writing some Google Apps Script to get each Google Group and list it's members then output it to a Google Sheet. Currently, I am grabbing each group and email address and pushing it to the memberArr, however I then want to 'merge' the relevant information.
So if for example, I have X Groups and Group 1 has 4 members (Foo, Bar, Baz and Quux) - Currently, it will output as
[ [ 'Group 1', 'Foo' ],
[ 'Group 1', 'Bar' ],
[ 'Group 1', 'Baz' ],
[ 'Group 1', 'Quux' ] ]
But I want to have it output as [Group 1, Foo, Bar, Baz, Quux].
That is to say, merge the contents of the memberArr where there is a common Group
Here is my code so far:
function getAllGroupsTEST() {
const groupArr = [];
let gPageToken;
let gPage;
do {
gPage = AdminDirectory.Groups.list({
customer: "my_customer",
maxResults: 100,
gPageToken
});
const groups = gPage.groups;
if (groups) {
groups.forEach(({email}) => {
const groupEmail = email;
groupArr.push(groupEmail);
});
}
gPageToken = gPage.nextPageToken;
} while (gPageToken);
console.log(`LOGGING GROUPS:\n\n${groupArr}`);
const memberArr = [];
let mPageToken;
let mPage;
groupArr.forEach(group => {
mPage = AdminDirectory.Members.list(group,{
customer: "my_customer",
maxResults: 500,
mPageToken
})
const members = mPage.members;
if (members) {
// console.log(`LOGGING ${members.length} MEMBERS FOR ${group}\n\n${members}`)
members.forEach(member => {
// console.log(`MEMBER: ${member.email} IS IN GROUP ${group}`)
memberArr.push([group, member.email])
})
}
})
// console.log(`COUNTED ${groupArr.length} GROUPS`)
// console.log(memberArr)
}
Any help would be greatly appreciated!
Edit: Updated to show the memberArr as is rather than in a table format.
I'd propose to convert the array in the object and then back to the array this way:
var arr = [
['group1','a'],
['group1','b'],
['group2','c'],
['group2','d'],
['group3','e']
]
var obj = {}
for (var a of arr) {
try { obj[a[0]].push(a[1]) }
catch(e) { obj[a[0]] = [a[1]] }
}
console.log(obj);
var new_arr = [];
for (var group in obj) {
new_arr.push([group, ...obj[group]])
}
console.log(new_arr);
Output:
[ [ 'group1', 'a', 'b' ], [ 'group2', 'c', 'd' ], [ 'group3', 'e' ] ]
I like #YuriKhristich solution. However, I still want to post this code showing how you could make a few minor changes to your existing code to build your required data structure.
We start by initializing a list with the group email. Next we append all the member emails to the list. And finally we push the completed list to memberArr. The advantage is that this builds the required data format while the data is read rather than trying to rework it afterward.
let list = [group]; // <-- ADD
if (members) {
members.forEach(member => {
// memberArr.push([group, member.email]) <-- REMOVE
list.push(member.email); // <-- ADD
})
memberArr.push(list); // <-- ADD
}
})
// Simulated Google Groups data
var gPage = {
groups: [
{id: 1, name: "Group 1", email: "group1#emal.com" },
{id: 2, name: "Group 2", email: "group2#emal.com" },
{id: 3, name: "Group 3", email: "group3#emal.com" }
]
};
var mPage = {
members: [
{id: 1, role: "admin", email: "member1#email.com" },
{id: 2, role: "admin", email: "member2#email.com" },
{id: 3, role: "admin", email: "member3#email.com" },
{id: 4, role: "admin", email: "member4#email.com" },
{id: 5, role: "admin", email: "member5#email.com" }
]
};
function getAllGroupsTEST() {
const groupArr = [];
let gPageToken;
//let gPage;
do {
/* useing fake data
gPage = AdminDirectory.Groups.list({
customer: "my_customer",
maxResults: 100,
gPageToken
});
*/
const groups = gPage.groups;
if (groups) {
groups.forEach(({email}) => {
const groupEmail = email;
groupArr.push(groupEmail);
});
}
gPageToken = gPage.nextPageToken;
} while (gPageToken);
const memberArr = [];
let mPageToken;
//let mPage;
groupArr.forEach(group => {
/* using fake data
mPage = AdminDirectory.Members.list(group,{
customer: "my_customer",
maxResults: 500,
mPageToken
})
*/
const members = mPage.members;
let list = [group];
if (members) {
members.forEach(member => {
// memberArr.push([group, member.email])
list.push(member.email);
})
memberArr.push(list);
}
})
return memberArr;
}
console.log( getAllGroupsTEST() );
You can implement this easy function for every group you want to filter
Take into account that this will eliminate every duplicate of the array.
const dataToFiler = [['Group 1', 'Foo'],
['Group 1', 'Bar'],
['Group 1', 'Baz'],
['Group 1', 'Quux']]
const filterRD = (arr) => {
return [...new Set(arr.flat())]
}
console.log(filterRD(dataToFiler))
Documentation
Set
Array.prototype.flat()

How create array containing all combinations of array 1-n array items?

We have the following task, to convert the array below called passengerFlights (object with passenger-id-keys and array of flights) to:
(1) an array with all possible combination of passenger-flights:
EXPECTED OUTPUT:
[
["aaa", "ddd", "eee"],
["aaa", "ddd", "fff"],
["bbb", "ddd", "eee"],
["bbb", "ddd", "fff"],
["ccc", "ddd", "eee"],
["ccc", "ddd", "fff"]
]
and (2) with the stipulation that there can be any number of passengers.
The following is an attempt to solve this first as a static example of three flights, although it's not clear the best way to (1) create the array with all possible combinations, and (2) how to solve the 2-n requirement, we assume recursion of some kind.
const passengerFlights = {
777: [
{
_id: "aaa"
},
{
_id: "bbb"
},
{
_id: "ccc"
}
],
888: [
{
_id: "ddd"
}
],
999: [
{
_id: "eee"
},
{
_id: "fff"
}
],
};
const getGroupedFlights = (passengerFlights) => {
let indexPointer = 0;
const indexCounters = [0, 0, 0];
const arr = [];
while (indexCounters[0] <= passengerFlights['777'].length - 1 || indexCounters[1] <= passengerFlights['888'].length - 1 || indexCounters[2] <= passengerFlights['999'].length - 1) {
arr.push([passengerFlights['777'][0]._id, passengerFlights['888'][0]._id, passengerFlights['999'][0]._id]);
if (indexCounters[2] < passengerFlights['999'].length) indexCounters[2]++;
if (indexCounters[2] >= passengerFlights['999'].length - 1 && indexCounters[1] < passengerFlights['888'].length) indexCounters[1]++;
if (indexCounters[1] >= passengerFlights['888'].length - 1 && indexCounters[0] < passengerFlights['777'].length) indexCounters[0]++;
console.log(indexCounters, passengerFlights['888'].length - 1);
}
return arr;
}
const groupedFlights = getGroupedFlights(passengerFlights);
console.log(groupedFlights);
It's just a simple recursive problem....
const
passengerFlights =
{ 777: [ { _id: 'aaa' }, { _id: 'bbb' }, { _id: 'ccc' } ]
, 888: [ { _id: 'ddd' } ]
, 999: [ { _id: 'eee' }, { _id: 'fff' } ]
}
, result = combinations( passengerFlights, '_id' )
;
console.log( showArr(result) )
function combinations( obj, KeyName )
{
let
result = []
, keys = Object.keys(obj) // [ "777", "888", "999" ]
, max = keys.length -1
;
f_recursif_combi(0)
return result
function f_recursif_combi( level, arr = [] )
{
obj[ keys[level] ] // like :passengerFlights['777']
.forEach( elm =>
{
let arr2 = [...arr, elm[KeyName] ]; // arr + elm['_id']
(level < max)
? f_recursif_combi(level +1, arr2 )
: result.push( arr2 )
})
}
}
// ************************************ just to present result...
function showArr(Arr)
{
const r = { '[["': `[ [ '`, '","': `', '`, '"],["': `' ]\n, [ '`, '"]]': `' ]\n]` }
return JSON
.stringify(result)
.replace(/\[\[\"|\"\,\"|\"\]\,\[\"|\"\]\]/g,(x)=>r[x])
}
.as-console-wrapper {max-height: 100%!important;top:0 }
I think it's the Cartesian product of flights sets. So this should help:
Cartesian product of multiple arrays in JavaScript
As another answer suggests, you can use a basic cartesian product function. Use Object.values(passengerFlights) to pass in the array of arrays.
function *product(arrs, p = []) {
if (arrs.length == 0)
yield p
else
for (const value of arrs[0])
yield *product(arrs.slice(1), [...p, value])
}
const passengerFlights =
{777: [{_id: "aaa"},{_id: "bbb"},{_id: "ccc"}],888: [{_id: "ddd"}],999: [{_id: "eee"},{_id: "fff"}]}
for (const p of product(Object.values(passengerFlights)))
console.log(JSON.stringify(p.map(obj => obj._id)))
I used JSON.stringify for easy visualization in the demo
["aaa","ddd","eee"]
["aaa","ddd","fff"]
["bbb","ddd","eee"]
["bbb","ddd","fff"]
["ccc","ddd","eee"]
["ccc","ddd","fff"]
But for your program you will probably prefer Array.from
console.log(
Array.from(
product(Object.values(passengerFlights)),
p => p.map(obj => obj._id)
)
)
[
["aaa","ddd","eee"],
["aaa","ddd","fff"],
["bbb","ddd","eee"],
["bbb","ddd","fff"],
["ccc","ddd","eee"],
["ccc","ddd","fff"]
]
Since the order of the expected result is not important, we can make the program more efficient.
function *product(arrs) {
if (arrs.length == 0)
yield []
else
for (const p of product(arrs.slice(1)))
for (const value of arrs[0])
yield [value, ...p]
}
const passengerFlights =
{777: [{_id: "aaa"},{_id: "bbb"},{_id: "ccc"}],888: [{_id: "ddd"}],999: [{_id: "eee"},{_id: "fff"}]}
for (const p of product(Object.values(passengerFlights)))
console.log(JSON.stringify(p.map(obj => obj._id)))
["aaa","ddd","eee"]
["bbb","ddd","eee"]
["ccc","ddd","eee"]
["aaa","ddd","fff"]
["bbb","ddd","fff"]
["ccc","ddd","fff"]

TS/JS - Get "value" from an Array of Objects if a Property of an Object from the Array matches another Property from a separate Object

THE PROBLEM:
I have an array of Objects. And a currentObject, that I currently am viewing. I want to get the value from a Property that comes from the Array of Objects, if 2 other properties match.
Here is the Array, simplified:
ARRAY = [{
id: 1,
metadata: {author: "Company1"}
},
{
id: 2,
metadata: {author: "Company2"}
}
Here is the Object, simplified:
OBJECT = {
name: "Something
templateId: 2
}
So, basically, I want to return, the metdata.author information, if the ARRAY.id, matches the OBJECT.templateId..
Here is the code I wrote..
const getAuthorInfo = (connTemplates: ARRAY[], currentConn: ITEM_OBJECT) => {
connTemplates.find((connTemplate: ARRAY_ITEM_OBJECT) => connTemplate.id === currentConn.templateId);
};
console.log('Author Info:', connection); // This though returns the OBJECT, not the ARRAY_ITEM
Any ideas, on how to make this work? I tried to filter as well, with the same condition, but that returned undefined, when I called it in my ReactComponent.
is this what you need?
const arr = [{
id: 1,
metadata: { author: "Company1" }
},
{
id: 2,
metadata: { author: "Company2" }
}]
const obj = {
name: "Something",
templateId: 2
}
function getAuthorInfo(arr, obj) {
const arrItem = arr.find(item => item.id === obj.templateId)
return arrItem.metadata.author
}
console.log(getAuthorInfo(arr, obj))
You are on the right path:
const result = arr.find(f => f.id == obj.templateId).metadata.author;
const arr = [{
id: 1,
metadata: {author: "Company1"}
},
{
id: 2,
metadata: {author: "Company2"}
}]
const obj = {
name: "Something",
templateId: 2
}
const result = arr.find(f => f.id == obj.templateId);
console.log(result);

Joining two arrays of JSON objects like an SQL join using functional programming

Consider, I have the following two arrays of objects:
const existingAndArchivedBookings =
[
{"booking_id":-2},
{"booking_id":-1},
{"booking_id":999}
]
const newAndExistingBookings =
[
{bookingId:-2, name: "name1"},
{bookingId:-3, name: "name1"},
{bookingId:-1, name: "namex"}
]
What I want to do is determine which of the bookings in the second array are new and which are existing. Any bookingId that is in both arrays is existing. Any bookingID that is in the second array but not the first is new. So, the result of the solution should be an array as follows:
[ { bookingId: -2, existing: true, name: 'name1' },
{ bookingId: -3, existing: false, name: 'name1' },
{ bookingId: -1, existing: true, name: 'namex' } ]
I have a solution (which I'll post as an answer), but I think there's probably a more efficient way of doing it. Good luck.
If you want a non-R answer: you can use a simple map to iterate over the data, compare the booking ids in both arrays (with some), and return a new array of objects.
const existingAndArchivedBookings = [{booking_id:-2},{booking_id:-1},{booking_id:999}];
const newAndExistingBookings = [{bookingId:-2, name: "name1"},{bookingId:-3, name: "name1"},{bookingId:-1, name: "namex"}];
function testBookings(arr1, arr2) {
return arr2.map(({ bookingId, name }) => {
const existing = arr1.some(obj => obj.booking_id === bookingId);
return { bookingId, existing, name };
});
}
const out = testBookings(existingAndArchivedBookings, newAndExistingBookings);
console.log(out);
You can greatly simplify it using Array.prototype.reduce to form the result of the comparisons between the 2 arrays and Array.prototype.findIndex to test whether the object in the second array is present in the first array:
const existingAndArchivedBookings =
[
{"booking_id":-2},
{"booking_id":-1},
{"booking_id":999}
]
const newAndExistingBookings =
[
{bookingId:-2, name: "name1"},
{bookingId:-3, name: "name1"},
{bookingId:-1, name: "namex"}
]
const res = newAndExistingBookings.reduce((acc, ele) => {
const idx = existingAndArchivedBookings.findIndex(b => b.booking_id === ele.bookingId);
let existing = false;
if(idx >=0 ){
existing = true;
}
return acc.concat({bookingId : `${ele.bookingId}`, existing: `${existing}`, name: `${ele.name}`});
}, []);
console.log(res);
Here's what I came up with, which seems a bit long winded
const R = require('ramda')
const existingAndArchivedBookings = [{"booking_id":-2},{"booking_id":-1},{"booking_id":999}]
const newAndExistingBookings = [{bookingId:-2, name: "name1"}, {bookingId:-3, name: "name1"}, {bookingId:-1, name: "namex"}]
const existingAndArchivedKeys = existingAndArchivedBookings.map(value => value.booking_id)
const newAndExistingKeys = newAndExistingBookings.map(value => value.bookingId)
const existingKeys = existingAndArchivedKeys.filter(key => newAndExistingKeys.includes(key))
const newKeys = newAndExistingKeys.filter(key => !existingAndArchivedKeys.includes(key))
const existingBookingIds = existingKeys.map(key => {
return {bookingId: key, existing: true}
})
const newBookingIds = newKeys.map(key => {
return {bookingId: key, existing: false}
})
const allArray = R.concat(newAndExistingBookings, R.concat(existingBookingIds, newBookingIds))
console.log(R.values(R.reduceBy(R.mergeLeft, {}, R.prop('bookingId'), allArray)))

How to update state of nested array of array of objects without mutating

I am tryin to update the state of nested array of objects, for instance add to results[0].rooms[2] -> loop rooms -> and add to each object room.sunday.flag
array of results:
results: [
{ dates:
{ weekstart: 2018-08-26T04:00:00.000Z,
weekend: 2018-09-02T03:59:59.000Z,
daysofweek: [Array] },
need: [ '103', '204', '12', '234', '34', '555', '44' ],
backorder:
[ '100', '102', '150', '403', '344', '12', '3434', '23', '44' ],
_id: 5b7b139465c29145d8d69ac2,
iscurrent: true,
isnext: false,
rooms: [ [Object], [Object], [Object], [Object] ],
user: 5b61b782719613486cdda7ec,
__v: 9 },
{ dates:
{ weekstart: 2018-09-02T04:00:00.000Z,
weekend: 2018-09-09T03:59:59.000Z,
daysofweek: [Array] },
need: [ '12', '13', '55', '45' ],
backorder: [ '10', '11', '112' ],
_id: 5b83fdc500b6b6dc493e9bb8,
iscurrent: false,
isnext: true, rooms: [ [Object], [Object], [Object],
[Object] ],
user: 5b61b782719613486cdda7ec,
__v: 9 }
]
my attempt to change the state without mutating
const resultsRooms = [
...this.state.results[0].rooms ];
const rooms = resultsRooms.map((room, roomIndex) =>
{
room.sunday.flag = true;
});
const resultsUpdaye = this.results.forEach((element, index) => {
if (index === 0) {
elsment.rooms = rooms;
}
});
this.setState({
results: resultsUpdaye
});
any help? what am i doin wrong
Your resultsRooms.map is wrong. First of all, it does not return an object. If you use an arrow function and want to return an object, you must enclose it with parentheses.
const foo = () => ( { foo: "bar" } );
If you don't do that the function sees {} as a body block.
Your second problem is, map returns an array, does not do operations on items. So you can't do this: room.sunday.flag = true;
Here is the working version:
const rooms = resultsRooms.map((room, roomIndex) =>
( { ...room, sunday: {...room["sunday"], flag: true } } )
);
So, we map the rooms, then return an object with spread syntax. With ...room we keep the parts of the room other than the sunday object. With sunday: {...room["sunday"], flag: true } we keep the parts of the sunday other than the flag property. Also, actually we don't need to make a copy with:
const resultsRooms = [
...this.state.results[0].rooms ];
Since we don't mutate it, with map we are creating a new array. So, here is the last version:
const rooms = results[0].rooms.map((room, roomIndex) =>
( { ...room, sunday: {...room["sunday"], flag: true } } )
);
This part is OK, we don't mutate the state but if you use forEach on results you mutate the original data. Don't do it.
Here is a concise and maybe a cleaner alternative without using forEach.
const newRooms = results[0].rooms.map( room =>
( { ...room, sunday: {...room["sunday"], flag: true } } )
);
const newItem = { ...results[0], rooms: newRooms };
const newResults = Object.assign([], results, { 0: newItem } );
Update after comments
I used Object.assign here to replace the item without mutating the original array. When using React (also if you prefer to use with React, this applies to Redux also) we should avoid mutating our data, namely our state. So, when you plan to change something in the state you should do it in proper ways. Your question actually indicates that: "without mutating". This is why I used Object.assign here.
I could choose other methods like:
const newResults = results.slice();
newResults[ 0 ] = newItem;
or
const newResults = [ ...results ];
newResults[ 0 ] = newItem;
Those are ok just for replacing the item as a whole. What do I mean here? slice and spread syntax does not create deep copies, they just do shallow copies. If you change a property of an object in the newly created array, the original one also mutates. This also applies to objects when we change nested properties. Actually, original source is objects here.
Here is an example array:
const arr = [
{ id:1, name:"foo" },
{ id:2, name:"bar" },
{ id:3, name:"baz" },
];
and an example item to change for index 2 (last item here);
const newItem = { id: 100, name: "change" };
const newArr = [ ...arr ];
arr[ 2 ] = newItem;
This is ok since we change a whole object here. Let's see:
const arr = [
{ id:1, name:"foo" },
{ id:2, name:"bar" },
{ id:3, name:"baz" },
];
const newItem = { id: 100, name: "change" };
const newArr = [ ...arr ];
newArr[ 2 ] = newItem;
console.log("new array", newArr );
console.log( "original array", arr );
Original one does not change. But if we do this:
newArr[ 2 ].id = 100; // ie, we only want to change the id, right?
Let's see:
const arr = [
{ id:1, name:"foo" },
{ id:2, name:"bar" },
{ id:3, name:"baz" },
];
const newArr = [ ...arr ];
newArr[ 2 ].id = 100;
console.log("new array", newArr );
console.log( "original array", arr );
So, our original array also changed. Mutation! If you don't change any property like this you can choose one of all three alternatives. But if you change a property you should think something better.
const arr = [
{ id:1, name:"foo" },
{ id:2, name:"bar" },
{ id:3, name:"baz" },
];
const newArr = Object.assign( [], arr, { 2: { ...arr[ 2 ], id: 100 } } );
console.log("new array", newArr );
console.log( "original array", arr );
Duh! :) Maybe there are better ways of doing this :) In any case, be very careful about mutating the state.
Just with an object:
const obj = {
user: {
id: 1,
name: "foo",
}
};
const newObj = { ...obj }
newObj.user.id = 1000
console.log( "new object", newObj );
console.log( "original object", obj );
Ok, this is enough for an explanation :)
Thank you for the answer. I am a bit confused, am I supposed to set
the state as follows: this.setState({ results: newResults });
Yes.
also what if i want to change the state of all results array rooms
results[0],results[1],results[2] .....
Come on, you have a great tool here :) map
const newResults = results.map( item => {
const newRooms = item.rooms.map( room =>
( { ...room, sunday: {...room["sunday"], flag: true } } )
);
const newItem = { ...item, rooms: newRooms };
return newItem;
})
First, we map the results, for each item, we map rooms and change the data, return the new item. So in the end, we get a new array where all its items changed, but again without any mutation.
I suggest playing a little bit with map, filter and maybe reduce methods. Also looking for spread syntax or if you prefer Object.assign is a plus.

Categories

Resources