简体   繁体   中英

How to dynamically select an object to a add property - js

I have two objects. I want to add new properties to them, but I want to select first which object to use. Here's the desired logic :

let myFn = (function() {

    // The Two Objects
    let university = {}
    let Person = {}

    let AddNewPropTo = ( objName , new_objProp ) => {
         return objName[new_objProp] = null;  // logic fail 1
    }
    let getProps = (objName) => {
       return Object.getOwnPropertyNames(objName)
    }

    return {
       AddNewPropTo,
       getProps
    }

})();

     myFn.AddNewPropTo('Person','Age'); // logic fail 2
     myFn.getProps(Person) // Desired Output : Person = { Age : null }

The error message at logic fail 1 tells you that you're trying to add a property to the string objName rather than the object.
So you need to select one of your objects,

let AddNewPropTo = ( objName , new_objProp ) => {
  if (objName === 'Person') {
    Person[new_objProp] = null
    return Person
  }
  if (objName === 'university') {
    university[new_objProp] = null
    return university
  } 
}

The second logic fail looks like a really basic mistake, the return value isn't captured

const Person = myFn.AddNewPropTo('Person','Age'); // logic fail 2
const props = myFn.getProps(Person) // Desired Output : Person = { Age : null }
console.log(props)

If you want to get more dynamic, try this

let university = {}
let Person = {}
const map = {
  'Person': Person,
  'university': university
}

let AddNewPropTo = ( objName , new_objProp ) => {
  let obj = map[objName]
  if (obj) {
    obj[new_objProp] = null
    return obj
  }
  return {}
}

I am not familiar with typescript but i got the result as like you want

Check this fiddle

Code:

let Person = {}

function AddNewPropTo( objName , new_objProp ) {
     return objName[new_objProp] = 1;  // logic fail 1
}
function getProps  (objName) {
   return Object.getOwnPropertyNames(objName);
}


 AddNewPropTo(Person,'Age'); 
 console.log(getProps(Person)) ; //returns ['Age']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM