简体   繁体   中英

javascript Object - access child property using dot notation

I created an object that requires a dictionary object be passed to initialize, and has attributes (like length ). I'd like to be able to simply access the dictionary's key : value pair by passing something like:

myNewObj['a'] or myNewObj.a

and not having to instead pass myNewObj.dictionary['a'] , but can't figure out how to do so.

Is there a way to set a dynamic attribute that, if no other attribute or method exits, will instead look into the dictionary and find the associated key?

var newObject = function(dictionary) {
    this.dictionary     = dictionary;
    this.length         = dictionary[[Object.keys(dictionary)[0]]].length;

    this.get = function (column) {
        return this.dictionary[[column]];
    }
};

var myNewObj = new newObject({
    a   : [1,2,3],
    b   : [4,5,6]
});

console.log(myNewObj.get('a'));

I've updated this to show a .get() method that works, but it's still not exactly what I'm looking for.

jsFiddle: http://jsfiddle.net/2uMjv/571/

Although this might not exactly fit your use case of dynamic attributes, the closest thing I can think of is extending the prototype. At least by using Object.setPrototypeOf * you can avoid defining each method individually and have a base set of functions to apply to each one of these newObject 's.

var newObject = function(dictionary) {
    this.dictionary = dictionary;
    this.length = dictionary[[Object.keys(dictionary)[0]]].length;

    this.get = function(column) {
        return this.dictionary[[column]];
    }
};

// Essentially a wrapper constructor.
var createNewObject = function(dictionary) {
    Object.setPrototypeOf(dictionary, new newObject(dictionary));
    return dictionary;
}

var myNewObj = createNewObject({
    a   : [1,2,3],
    b   : [4,5,6]
});

console.log(myNewObj['a']);
console.log(myNewObj.get('b'));

* You may want to look at the potential drawbacks in using this.

Why don't you just set properties? :

 class Dictionary {
  constructor(dictionary) {
   Object.assign(this, dictionary);
  }

  get length() {
    return Object.keys(this).length;
  }

  get(column) {
    return this[column];
  }
}

var dict = new Dictionary({
  a   : [1,2,3],
  b   : [4,5,6]
});

console.log(dict.a, dict["a"], dict.get("a"));

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