I am experimenting with how to merge two variables and it is an object?
I have tried with this which seem to work:
let data1 = {
data1: "data1"
}
let data2 = {
data2: "data2"
}
const items = {
...(data1 && typeof data1 === 'object' && { ...data1 }),
...(data2 && typeof data2 === 'object' && { ...data2 }),
}
console.log(items);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This is good or unless I am overcomplicating this?
CodePudding user response:
...if variable exist...
If you mean that literally, the variable may not be declared, then you need to move the typeof
check to the front in order to avoid trying to read the value of an undeclared variable. You can also take advantage of the fact that spreading undefined
, null
, or a boolean (like false
) doesn't do anything (including not causing an error).
Here I've added a data3
that doesn't exist to show that part in action:
let data1 = {
data1: "data1",
};
let data2 = {
data2: "data2",
};
const items = {
...typeof data1 === "object" && data1,
...typeof data2 === "object" && data2,
...typeof data3 === "object" && data3,
};
console.log(items);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
How that works (using data1
as the example):
typeof data1 === "object"
tells us two things:- That there's an in-scope identifier called
data1
(which means we can read its value without worrying about getting aReferenceError
for an undeclared variable) - That
data1
's value is of type"object"
- That there's an in-scope identifier called
- That combined with
&& data1
means we'll be using one of these values with spread:false
iftypeof data1 === "object"
isfalse
, or- The value of
data1
, which is either an object ornull
Spreading null
doesn't do anything, and spreading false
doesn't do anything, so we either get no properties from that spread operation or we get the own, enumerable properties of an object that data1
references.