skip to Main Content

I have a Javascript object otherObj and I construct myObj dynamically based on non-undefined values of otherObj. As of now, I manually compare and assign as below. But was wondering if there can be a more efficient way…Also not sure if it is possible to make it even more dynamic i.e. say if attr3 gets added in future, that also gets considered automatically.

let myObj = {};
if (otherObj.attr1 !== undefined) {
    myObj['attr1'] = otherObj.attr1;
}
if (otherObj.attr2 !== undefined) {
    myObj['attr2'] = otherObj.attr2;
}

2

Answers


  1. You can try using for…in to iterate over the properties of otherObj and conditionally assign them to myObj:

    let myObj = {};
    
    for (let prop in otherObj) {
      if (otherObj[prop] !== undefined) {
        myObj[prop] = otherObj[prop];
      }
    }
    
    Login or Signup to reply.
  2. You can use the Nullish coalescing operator

    ["attr1","attr2"].forEach(attr = myObj[attr] = otherObj[attr] ?? "";
    

    Be careful if the otherObj[attr] is an object. You will need to clone it if you do not want subsequent actions on myObj to affect otherObj

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search