0 votes
in Education by (1.7m points)
I'm going to be getting an array of objects and want to set instance variables inside of a class based on a property. So if I get this:

ary = [{type: 'walrus', name: 'GorbyPuff'}, {type: 'humanoid', occupation: 'KingSlayer'}]

I want to initialize an object where @walrus == ary[0] and @humanoid == ary[1]

In Ruby I could user instance_variable_set, but how can this be accomplished in the Javascripts?

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by (1.7m points)
I'm not sure if I get what you're trying to acchieve, but the easiest way to do this would be:

var theObj = {};

for(var i=0;i<ary.length;i++)

{

    theObj[ary[i].type] = ary[i];

}

The worry here is, that by altering the ary variable you will inadvertently alter the theObj:

console.log(theObj.walrus.name);//Outputs: GorbyPuff

ary[0].name = 'Nips!';

console.log(theObj.walrus.name);//Outputs: Nips! <-- objects are passed by reference, always

If the ary variable is part of a function scope, and the resulting object is its return value, you needn't worry. But if both are part of the global scope (Which they shouldn't, it's bad practice), this becomes an issue.

I therefore propose this approach:

var obj = {};

var i;

while (ary.length !== 0)

{

    i = ary.splice(0,1)[0];//removes element from array

    if (i.hasOwnProperty('type'))//always best to check the property you're going to use is there

    {

        obj[i.type] = i;

    }

}
...