I want to check if a property in a first object exists within a second object and change it's value if it's different, dinamically. The first object properties may change because it's created dinamically too, and the second object's properties are always the same.
The logic I need to find it's the following, but instead of doing it manually (checking every property and value with a different if clause) is there any way of creating a function that does this dinamically? I am using vanilla javascript
function mapObject2(obj1) {
if (sessionStorage.getItem("obj2") != null) {
var obj2 = JSON.parse(sessionStorage.getItem("obj2"))
if (obj1.Color != obj2.Color) {
obj1.Color = obj2.Color
}
}
}
You can use Object.assign() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
function mapObject2(obj1) {
if (sessionStorage.getItem("obj2") != null) {
var obj2 = JSON.parse(sessionStorage.getItem("obj2"))
Object.assign(obj1, obj2)
}
}
You can use Object.assing as @krasi said but the correct syntax is this
function mapObject2(obj1) {
if (sessionStorage.getItem("obj2") != null) {
var obj2 = JSON.parse(sessionStorage.getItem("obj2"))
Object.assign(obj1, obj2)
}
}
if you want to return a new object that is the merge of obj1 and obj2 you can do this
function mapObject2(obj1) {
if (sessionStorage.getItem("obj2") != null) {
const obj2 = JSON.parse(sessionStorage.getItem("obj2"))
return {...obj1, ...obj2}
//or
return Object.assign({}, obj1, obj2)
}
return obj1
}
function mapObject2(obj1) {
if (sessionStorage.getItem("obj2") != null) {
const obj2 = JSON.parse(sessionStorage.getItem("obj2"))
Object.keys(obj1).forEach(k => {
obj1[k] = obj2[k] || obj1[k]
})
}
}