user9229318
user9229318

Reputation:

(JavaScript) How to check JSON for key

I have an endpoint for my API where it receives the body:

{
    "id" : 101,
    "value1" : 1,
    "value2" : 2,
    "value3" : 3
}

I then perform a query that updates the table with value1, value2 and value3 where id = id. However, I want to create something that checks if a key is present.

For example, I may only want to update value2, thus sending the following in the body:

{
    "id" : 101,
    "value2" : 2
}

I need my sql function to only perform:"UPDATE table SET value2 = ?, WHERE id = ?";

I would assume that the solution to this would be to have a for-loop to check for keys present in the object. If they are present create a variable, data which stores value1 = a, value2 = b, value3, =c?

Would this be the correct way, and if so how do I check if something is present in an object?

Upvotes: 0

Views: 86

Answers (2)

Zevgon
Zevgon

Reputation: 644

I believe the best way to do this is to use hasOwnProperty:

const obj = {'a': 1, 'b': null};
console.log(obj.hasOwnProperty('a'));
console.log(obj.hasOwnProperty('b'));
console.log(obj.hasOwnProperty('c'));

Upvotes: 0

Vinayak
Vinayak

Reputation: 161

If you just want to check that JavaScript object key has any value or not:

if(obj['key'])
//If value present
else
//No value

Upvotes: 0

Related Questions