Wednesday, 31 May 2017

How to check two objects for difference in values in JS?

I want to edit a existing user in Node. My front-end is in pug. My user table has lots of fields (about 20 to 25), and some have to be unique, like email and username, which I have functions to check if they are not a duplicate.

I only want to update values that has changed on the client, my edit form already has the values of the user of course.

I thought the best way to achieve this is to check all the inputs from req.body, and if it is different from any user values, I should update it. (Perhaps any different methods? Can't I check if the inputs are 'dirty'?)

This could be the situation. Note the req.body object, with values that my user table doesn't have, like password_confirm

req.body = { 
    username: 'test',
    email: 'user@user.com', 
    password: '1234',
    password_confirm: '1234',
    location: 'New York',
    website: 'new-website.com',
    bio: undefined,
    expertise: 'New expertise'
}
user = { 
    username: 'test',
    email: 'user@user.com', 
    password: '1234',
    location: 'San Fransico',
    website: 'website.com',
    bio: null,
    expertise: null
}

I now only want to update the changed location, website and expertise fields. I tried many things, using reduce and lodash, but I can't get the fields that I'm looking for.

NB I already checked different StackOverflow questions but nothing seems to work for my situation..



via Fabian Tjoe A On

No comments:

Post a Comment