Search code examples
javascriptjqueryobjectname

How do I get specific object's attributes after a related event?


I'm not sure my title is clear, but let's take a look.

I have 2 li elements in a ul list, and I want that when I click a li, to get the text of the li and then create an object based on the phones variable.

Example : when I click NEXUS, get a Phone object in my console with attributes :

models: ['5', '6', '5X', '6P'];

Unfortunately, I get i can't pass the constructor name to the return of the function setConstructor(). I tried to write the "modelname" with {} and (), but the code didn't execute at all.

How can I do this?

var phones = {
    NEXUS: {
        name: 'Nexus',
        models: ['5', '6', '5X', '6P']
    },
    IPHONE: {
        name: 'iPhone',
        models: ['5', '5S', '6', '6S']
    }
};

var lastConstructorClicked = {};
var output = {};

function Phone(constructorModels) {
    this.models = constructorModels;
    this.getModels = function () {
        return this.models;
    };
}

function setConstructor(modelname) {
	return phones.modelname.models;   
}

$("a[id^='show-models-']").click(function() {
    lastConstructorClicked = $(this).text();
    console.log(lastConstructorClicked);
	output = new Phone(setConstructor(lastConstructorClicked));
});

console.log(output);
<ul class="dropdown-menu">
    <li><a href="#" id="show-models-iphone">IPHONE</a></li>
    <li><a href="#" id="show-models-nexus">NEXUS</a></li>
</ul>


Solution

  • phones.modelname.models is going to look for a member actually named modelname, not the member named by that variable. You want:

    phones[modelname].models
    

    var phones = {
      NEXUS: {
        name: 'Nexus',
        models: ['5', '6', '5X', '6P']
      },
      IPHONE: {
        name: 'iPhone',
        models: ['5', '5S', '6', '6S']
      }
    };
    
    var lastConstructorClicked = "";
    var output = {};
    
    function Phone(constructorModels) {
      this.models = constructorModels;
      this.getModels = function() {
        return this.models;
      };
    }
    
    function setConstructor(modelname) {
      return phones[modelname].models;
    }
    
    $("a[id^='show-models-']").click(function(e) {
      e.preventDefault();
    
      lastConstructorClicked = $(this).text();
      console.log(lastConstructorClicked);
      output = new Phone(setConstructor(lastConstructorClicked));
      console.log(output);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <ul class="dropdown-menu">
      <li><a href="#" id="show-models-iphone">IPHONE</a>
      </li>
      <li><a href="#" id="show-models-nexus">NEXUS</a>
      </li>
    </ul>