Does _.find return a reference to the object? How to properly set a property of the result?

Viewed 3997

I use lodash find to query object from array, then I set the property of that object but when I print out the array after setting this property, it is unchanged.

I would be grateful for some comments from someone more experienced on handling objects with lodash in JavaScript. Feel also free to comment on the way I formulate the problem or to edit the content to make it more easily searchable for other people via search engines.

Isolated code:

console.log('socket.io', token);
console.log(realtime);
let session = yield _.find(realtime, function(data) {
    return data.token === token;
});
console.log('session object to be set');
console.log(session);
if (!session.socket) {
    console.log('setting session for '+session.token+' socket '+socket.id);
    session.socket = socket.id;
    console.log('local reference after set');
    console.log(session);
    console.log('realtime after set');
    console.log(realtime);
}

Result, this is the output from console.log:

socket.io 268fc477-d4ee-4ed4-88cd-648539397df2
[ { token: '268fc477-d4ee-4ed4-88cd-648539397df2' } ]
session object to be set
{ token: '268fc477-d4ee-4ed4-88cd-648539397df2' }
setting session for 268fc477-d4ee-4ed4-88cd-648539397df2 socket /#iEqqcIsBbATDs1a-AAAB
local reference after set
{ token: '268fc477-d4ee-4ed4-88cd-648539397df2',
socket: '/#iEqqcIsBbATDs1a-AAAB' }
realtime after set
[ { token: '268fc477-d4ee-4ed4-88cd-648539397df2' } ]

Expected result, look at the last print, I want this object to be modified in the data structure that object originated from:

socket.io 268fc477-d4ee-4ed4-88cd-648539397df2
[ { token: '268fc477-d4ee-4ed4-88cd-648539397df2' } ]
session object to be set
{ token: '268fc477-d4ee-4ed4-88cd-648539397df2' }
setting session for 268fc477-d4ee-4ed4-88cd-648539397df2 socket /#iEqqcIsBbATDs1a-AAAB
local reference after set
{ token: '268fc477-d4ee-4ed4-88cd-648539397df2',
socket: '/#iEqqcIsBbATDs1a-AAAB' }
realtime after set
[ {
token: '268fc477-d4ee-4ed4-88cd-648539397df2',
socket: '/#iEqqcIsBbATDs1a-AAAB'
} ]

Public gist, feel free to also comment here. I hope this question will be also useful for others.

Edit Lodash reference says Returns the matched element, else undefined. I am not sure if that means that it returns cloned object or reference to queried object.

1 Answers
Related