Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
How to merge objects if variable exist and it is an object?

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);

This is good or unless I am overcomplicating this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

...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);

How that works (using data1 as the example):

  1. 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 a ReferenceError for an undeclared variable)
    • That data1's value is of type "object"
  2. That combined with && data1 means we'll be using one of these values with spread:
    • false if typeof data1 === "object" is false, or
    • The value of data1, which is either an object or null

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!