0

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

1
  • could you post your code? Commented Aug 1, 2014 at 9:51

5 Answers 5

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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]]);

Comments

0

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.

Comments

0
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]])

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.