0

I asked myself a question to optimize my code in JavaScript. I am currently doing something like this :

Data.json :

{
  "House" :
    { "bedroom"  : "4" }
    { "kitchen"  : "1" }
    { "bathroom" : "2" }
}

Choose.js :

var Data = require('./Data.json');

printData = function(id) {
  console.log(getData(id));
}

getData = function(id) {
  switch (id) {
    case "bedroom":
      return Data.House.bedroom;
    case "kitchen":
      return Data.House.kitchen;
    case "bathroom":
      return Data.House.bathroom;
    default:
      break;
  }
}

And I would like to know if we could optimize this with a special syntax, for example if we simply have :

var Data = require('./Data.json');

printData = function(id) {
  console.log(Data.House.{ id });
}

I know this might be a stupid question for you but it would be helpful if you tell me if it's possible or not. I wish I could avoid very long Switch Cases in my project.

Thanks.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Pol Grisart
  • 179
  • 4
  • 13

3 Answers3

3

Use [] notation

printData=function(id){
    return Data.House[id];
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

You can do it:

var Data = {
  "House" : { 
    "bedroom"  : "4", 
    "kitchen"  : "1",
    "bathroom" : "2" 
  }
};

getData = function(id) {
  return Data.House[id];
}

console.log(getData('bedroom'));
console.log(getData('kitchen'));
console.log(getData('xxx'));
Faly
  • 13,291
  • 2
  • 19
  • 37
1
getData=function(id){
   if(Data.House.hasOwnProperty(id)) return Data.House[id];
    return '';
}
LellisMoon
  • 4,810
  • 2
  • 12
  • 24