如何动态选择对象添加属性 - js

时间:2017-10-24 23:56:17

标签: javascript typescript

我有两个对象。我想为它们添加新属性,但我想首先选择要使用的对象。这是理想的逻辑:

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 }

2 个答案:

答案 0 :(得分:1)

逻辑失败1时的错误消息告诉您,您正在尝试将属性添加到字符串objName而不是对象。
所以你需要选择一个对象,

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

第二个逻辑失败看起来像一个非常基本的错误,返回值未被捕获

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

如果你想获得更多动态,试试这个

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 {}
}

答案 1 :(得分:0)

我不熟悉打字稿,但我得到的结果就像你想要的那样

选中此fiddle

代码:

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']