-1
console.log (articles[0].title);
console.log (articles[0].media[0].copyright);

->this works!

but all 3 bracket notation below does not! Obvious mistake?? I need to access "media-metadata" and because of special character is need brackets right? Its explained everywhere and seem straighforward but then I have no idea why it is not working.

console.log (articles[0].media[0].['media-metadata']);
console.log (articles.[0]['media'][0]);
console.log (['articles'][0]['media'][0]['media-metadata'][0]['url'][2]);

thanks for help !

json is copyrighted and complicated, but i checked the hierarchies over and over.

dumpman
  • 27
  • 4

2 Answers2

1

There are multiple problems:

Line 1:

console.log (articles[0].media[0].['media-metadata']);

The .['media-metadata'] is wrong, remove the dot such that it becomes

console.log (articles[0].media[0]['media-metadata']);

You can use either dot or the brackets to access nested properties, for numerically indexed properties or properties containing some special characters (like -) which are not allowed in a property identifier or variable, the bracket notation is mandatory.

Line 2:

console.log (articles.[0]['media'][0]);

articles.[0] is invalid, it should be articles[0]:

console.log (articles[0]['media'][0]);

Again, you have used both a dot and the brackets.

Line 3:

console.log (['articles'][0]['media'][0]['media-metadata'][0]['url'][2]);

The first part of wrong, instead of beginning with ['articles'] you should use articles:

console.log (articles[0]['media'][0]['media-metadata'][0]['url'][2]);

While your expression is syntactically okay, it does not mean what you want (the first part was an array containing one element which is the text "articles") - you probably want to use the object stored in the variable called articles.

Hero Wanders
  • 3,237
  • 1
  • 10
  • 14
1

The way an object works is like this

var obj = {
 foo: bar,
 foo2: [
    bar1, bar2, bar3
 ],
 foo3: {
     prop1: 1,
     prop2: 2,
     prop3: 3
  }
 };

We can access its values using either the "." notation or the ["property"] notation but not both, however we can combine them like so:

obj.foo === obj["foo"] //true, they are both bar
obj.foo2[2] === obj["foo2"][2] //true, they are both bar3

//I know syntactically this is incorrect but they are all the equivalent
obj.foo3.prop3 === obj["foo3"]["prop3"] === obj.foo3["prop3"] === obj["foo3"].prop3
Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18