0

Here is an explanation of what I want. let's say we have an array of objects.

the first console.log works as expected but I can't make the second one work correctly... I want the second console.log to do the same thing as the first one.

How can do this?

     var sentences = [
    { passed: {mean: 10, shadow: 11, write: 12}}
];
        
        let a = 'mean';
        console.log(sentences[0].passed.mean)
        console.log(sentences[0].passed.a);
Sara Ree
  • 2,963
  • 9
  • 31

2 Answers2

3

console.log(sentences[0].passed[a])

This uses a as a variable.

Michael Bianconi
  • 4,942
  • 1
  • 8
  • 23
1

You can use bracket notation for this:

var sentences = [{
  passed: {
    mean: 10,
    shadow: 11,
    write: 12
  }
}];

let a = 'mean';
console.log(sentences[0].passed.mean)
//Like this:
console.log(sentences[0]['passed'][a]);
//or this:
console.log(sentences[0].passed[a]);

Since a is a variable, you need use bracket notation to get the value from the object's corresponding property (dot-notation won't work in that way)

Tom O.
  • 5,449
  • 2
  • 20
  • 35