-3

I am working on the demo code below. Why am I not able to extract values from the object?

var obj = {
  webSiteName: 'StackOverFlow',
  find: 'anything',
  onDays: ['sun', 'mon',
    'tue',
    'wed',
    'thu',
    'fri',
    'sat',
    {
      name: "jack",
      age: 34
    },
    {
      manyNames: ["Narayan", "Payal", "Suraj"]
    },
  ]
};


console.log(obj.onDays[2]);
console.log(obj.onDays.manyNames[1]);
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • The first one works fine, the second should be `obj.onDays[8].manyNames[1]` – 4castle Oct 02 '17 at 04:12
  • 1
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – 4castle Oct 02 '17 at 04:47

2 Answers2

1

The manyNames object is at the 8th index of the array, so therefore you need this:

console.log(obj.onDays[8].manyNames[1]);

For jack:

console.log(obj.onDays[7].name);

Or age:

onsole.log(obj.onDays[7].age);
Dream_Cap
  • 2,292
  • 2
  • 18
  • 30
  • Thanks Dream_Cap can you pleas also let me know how can I get name of `jack` as well? I mean how I can query with `name` or `age` – Behseini Oct 02 '17 at 04:17
0

You should understand the basic difference between array and object.

Whenever you deal with an Array, access by index.

arr[index]; // obj["onDays"][7]["name"];

Whenever you deal with an Object, access by the property.

obj[property] or obj.property // obj["find"];
prabhatojha
  • 1,925
  • 17
  • 30