-1

Sorry maybe very easy for someone, but how can I get the value from this array?

        this.optionSelect = [{value: 'aa', name: 'ccc'}];

I tried :

console.log( this.optionSelect['value']); 

also `

console.log( this.optionSelect[0]);`
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Darksymphony
  • 2,155
  • 30
  • 54
  • 4
    Try `this.optionSelect[0].value` – Nikhil Aggarwal Apr 26 '19 at 11:36
  • 1
    Possible duplicate of [How can I access and process nested objects and arrays?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-and-arrays) – DTul Apr 26 '19 at 11:39

3 Answers3

4

They are multiple level to need to interact with.

First level is the array. You can see it's an array because of the delimiting characters [ ] :

[{value: 'aa', name: 'ccc'}];

You access the first element of the array using an index, like : this.optionSelect[0]


Then you have to deal with an object. You can see it's an object because of the delimiting characters { } :

{value: 'aa', name: 'ccc'}

To access an object, you have to use the name of the key you want, like : obj.value or obj['value'].

Both notation works.


Now do both in the same line :

this.optionSelect[0].value
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
1

You can reach this value by the following. Arrays are Indexed, the 0 is which index in the array you are accessing so. JavaScript Arrays.

this.optionSelect[0] will be -> {value: 'aa', name: 'ccc'};

Then add .value as the key you want to access of the object. Property access.

console.log(this.optionSelect[0].value);
devDan
  • 5,969
  • 3
  • 21
  • 40
0

Get the value of the first item in the array:

const value = this.optionSelect[0].value;

Also try destructuring:

const [{ value }] = this.optionSelect;
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79