How to convert string as object's field name in javascript

前端 未结 5 999
北恋
北恋 2020-11-28 08:38

I have a js object like:

obj = {
  name: \'js\',
  age: 20
};

now i want to access name field of obj, but i can only get string \'name\', s

相关标签:
5条回答
  • 2020-11-28 09:14

    As objects are associative arrays in javascript you can access the 'name' field as obj['name'] or obj[fieldName] where fieldName = 'name'.

    0 讨论(0)
  • 2020-11-28 09:24

    You can access the properties of javascript object using the index i.e.

    var obj = {
      name: 'js',
      age: 20
    };
    
    var isSame = (obj["name"] == obj.name)
    alert(isSame);
    
    var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
    isSame = (obj[nameIndex] == obj.name)
    

    Check example@ : http://www.jsfiddle.net/W8EAr/

    0 讨论(0)
  • 2020-11-28 09:26

    In Javascript, obj.name is equivalent to obj['name'], which adds the necessary indirection.

    In your example:

    var fieldName = 'name'
    var obj = {
      name: 'js',
      age: 20
    };
    var value = obj[fieldName]; // 'js'
    
    0 讨论(0)
  • 2020-11-28 09:27

    Not related at all, but for anyone trying to define object's field name from a string variable, you could try with:

    const field = 'asdf'
    const obj = {[field]: 123}
    document.body.innerHTML = obj.asdf

    0 讨论(0)
  • 2020-11-28 09:32

    It's quite simple, to access an object's value via a variable, you use square brackets:

    var property = 'name';
    var obj = {name: 'js'};
    alert(obj[property]); // pops 'js'
    
    0 讨论(0)
提交回复
热议问题