0

I don't understand how I can access an value in a object that is an array with an object inside itself.

I've tried with the dot notation and [] and array.reduce. But I'm doing something wrong.

I've changed the values but the structure remains the same:

"test": {
  "title": "My title",
  "category": null,
  "info": [{
    "time": 10,
    "type": "minutes"
  }]
}

I need to get the values of time and type, but I get undefined.

adiga
  • 34,372
  • 9
  • 61
  • 83
Sebastian
  • 13
  • 7
  • Assuming that `test` is a property of an object `obj`, then you can simply use `obj['test']['info'][0][time']` and `obj['test']['info'][0]['type']`. Though, maybe you are fetchinf these data, so there might be synch problem. Where do you get this `test` object? – Jolly May 23 '19 at 09:40
  • Thanks @MaheerAli, I forgot the `[0]` :) – Jolly May 23 '19 at 09:43

2 Answers2

0

The final object is first element of array so you need to first access its first element.

const obj = {
  "test": {
    "title": "My title",
    "category": null,
    "info": [{
      "time": 10,
      "type": "minutes"
    }]
  }
}
console.log(obj.test.info[0].time);
console.log(obj.test.info[0].type);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

Use the dot notation to access the properties Object a consists of the test object which in-turn contains the key info whose value is an array containing one object with the required keys

a->test->info->[{time,type}]

var a = {
  "test": {
    "title": "My title",
    "category": null,
    "info": [{
      "time": 10,
      "type": "minutes"
    }]
  }
}

console.log(a.test.info[0].time)
console.log(a.test.info[0].type)
ellipsis
  • 12,049
  • 2
  • 17
  • 33