Reputation: 8526
how do I destructure an object only when key is present in the object or should I say destructuring using conditionals
const arts = { a: 23, b: 3, c: 5}
const {a, d} = arts
console.log(d)
// result produces an error on execution
I want a code where "d" won't be destructured if it's not a key available in the object.
Upvotes: 2
Views: 3192
Reputation: 51
You could also try to use a default value for the properties like so:
const arts = { a: 23, b: 3, c: 5}
const {a = undefined, // The default could be 0 if it works for your use case.
d = undefined,
} = arts
console.log(d) // logs: 'undefined'
console.log(a) // logs: 23
Upvotes: 3
Reputation: 446
const arts = { a: 23, b: 3, c: 5}
if(arts.hasOwnProperty('a')) {
const {a} = arts
console.log(a)
// do something with a
}
else {
console.log('a was not found in arts');
}
if(arts.hasOwnProperty('d')) {
const {d} = arts
console.log(d)
// do something with d
}
else {
console.log('d was not found in arts');
}
Using arts
as defined above will output:
23
d was not found in arts
The hasOwnProperty()
method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
Upvotes: 1