ScottRedrup
ScottRedrup

Reputation: 91

Javascript, turn string into object attribute

I am wondering if it is possible to have an object with some attributes for example:

object name: Human

this.age = 8
this.name = "Steve"

Then have an array of strings which contain each attribute to that object such as:

manAttributes = ["age","name"]

So therefore if i wrote

console.log(Human.manAttributes[0])

The console should log '8' But this doesn't work, I get unexpected string.

Thanks

Upvotes: 0

Views: 694

Answers (5)

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

if you are looking at iterating through the properties, i would suggest the following approach.

var human = {      
  name: "Smith",
  age: "29"      
};

var manAttributes = ["age","name"];

for(var prop in manAttributes){
  if(human.hasOwnProperty(manAttributes[prop])){
    console.log(human[manAttributes[prop]]);
  }  
} 

DEMO

Upvotes: 0

BeachAndBytes
BeachAndBytes

Reputation: 131

function Human(age,name) {
  this.age = age;
  this.name = name;
}
var self = new Human(8,'Steve');

var humanProperties = Object.getOwnPropertyNames(self);

console.log(self[humanProperties[0]])

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

You'd be needing:

Human[manAttributes[0]]

The [] syntax being the way of accessing a property by (variable) name rather than by constant literal token.

Upvotes: 0

Eric Redon
Eric Redon

Reputation: 1762

Object properties can be accessed through either dot notation or bracket notation (see Mozilla's JavaScript reference).

So, this will output what you want:

console.log(Human[manAttributes[0]]);

Upvotes: 0

Rajesh
Rajesh

Reputation: 3778

An object is a key:value pair. The key and value are separated by a : (colon). In your case, you have separated by =. Change your code as below:

 var Human = {
     manAttributes: ["age","name"],
     age: 8
 };
 alert(Human[Human.manAttributes[0]]);  //alerts 8

This solution considers manAttributes as a property of Human object. If manAttributes is a separate array outside the Human object, then,

 var manAttributes = ["age","name"];
 var Human = {
     age: 8
 };
 alert(Human[manAttributes[0]]);  //alerts 8

Upvotes: 1

Related Questions