简体   繁体   中英

How to automatically assign value to another key depending on some other key's value in an Object

How do you achieve the following thing in Javascript

1) var MyObject={
2)    tableView:true,
3)    chartView:!(this.tableView)
4) }

The code at line number 3 is not working. Whats wrong in that line?

What i basically want to do is set "chartView" to opposite of "tableView" whenever tableView is set from code.

Since you're in the process of creating the object, this is not bound to that object. Moreover, since you want chartView to always evaluate to the opposite of tableView , even if the latter changes further down the line, a function would be a better approach:

var MyObject = {
    tableView: true,
    chartView: function() {
        return !this.tableView;
    }
};

Now you can do:

var chartView = MyObject.chartView();  // false.
MyObject.tableView = false;
chartView = MyObject.chartView();      // true.

You can't use this to refer to an object in an object literal's properties. You can use this inside a function that is a method of that object:

var MyObject = {
  tableView: true,
  chartView: function () {
    return !this.tableView;
  }
}

Based on your requirement, this may be an answer too,

 var MyObject = {
      view : function(bool){
         this.tableView = bool;
         this.chartView = !(bool); 
      }
      tableView: true,
      chartView: false
    } 

    MyObject.view(false)

    console.log(MyObject.tableView);     // Outputs false
    console.log(MyObject.chartView)      // Outputs true

This way you will always have opposite of tableView in chartView with a single function call.

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