Reputation: 25
Hey I'm trying to fill out an empty placeholder object (which in this case serves as a v-model for vue, but not important exactly to the case). The object that I'm expanding the original with may or may not have some objects inside it undefined, but i need to keep the structure of the first object no matter the structure of incoming one. For example Object 1
let object1 = { a : '', b : '', c : {name : 'Mark', title: 'Mr'}}
and Object 2 which will sometimes come like this
let object2 = { a : 'AAA', b : 'BBB', c : undefined}
I need to keep the structure of object 1 even if the other object has the property c undefined. In this case
let object1 = { a : 'AAA', b : 'BBB', c : {name : 'Mark', title: 'Mr'}}
Thanks
Upvotes: 0
Views: 505
Reputation: 45121
If you want to use spread syntax you could define a simple helper proxy that filters own keys to those having values other than undefined
let object1 = {a: '', b: '', c: {name: 'Mark', title: 'Mr'}}
let object2 = {a: 'AAA', b: 'BBB', c: undefined}
const result = { ...defined(object1), ...defined(object2) }
console.log(result)
function defined(obj) {
return new Proxy(obj, {
ownKeys() {
return Object.keys(obj).filter(key => obj[key] !== undefined)
}
})
}
Upvotes: 0
Reputation: 1
Try to spread the object2
as first item, then add property c
as second :
object1={...object2,c:object1.c}
or
object1={...object2, c : object2.c ? object2.c : object1.c}
Upvotes: 2