romuald lecorroller
romuald lecorroller

Reputation: 1

spread and destructuring object

I have this code :

function logInfos(user = {}) {
  const redactedUser = {
    firstName: "<REDACTED>",
    lastName: "<REDACTED>",
    address: {
      city: "<REDACTED>",
      country: "<REDACTED>",
    },
  };

  const {
    firstName,
    lastName,
    address: { city, country },
  } = user;

  console.log("partie user", firstName);
  console.log("partie user", lastName);

  const newUser = {
    ...user,
    address: {
      ...user.address,
    },
  };
  console.log("partie newuser", newUser);

  console.log(`${newUser.firstName} ${newUser.lastName} lives in ${newUser.address.city}, ${newUser.address.country}.`);
}

How can I replace the value undefined of user object passed as argument and use the default value of redactedUser object instead?

Upvotes: 0

Views: 59

Answers (1)

Bishwajit Pradhan
Bishwajit Pradhan

Reputation: 21

function compareObj(defaultObj, targetObj) {
for(let key in defaultObj) {
  if(!Array.isArray(defaultObj[key]) && defaultObj[key] !== null && typeof defaultObj[key] === "object") {
    targetObj[key] = {};
    copyObj(defaultObj[key], targetObj[key]); 
  } else {
    if(!targetObj[key]) targetObj[key] = defaultObj[key];
  }
}

}

compareObj(redactedUser, user);

You can place this code function inside logInfos. What it does is, it iterates through all the properties of the default object and checks if the property exists in the target object. In case the property does not exist in the target object, same property will be created in the target object and the value will be copied.

Upvotes: 1

Related Questions