0

I have been starting to look at javascript objects, and I have found the format that looks like this.

var obj = {
        prop1: 5,
        obj2: {
          prop1: [3, 6, 3],
          prop2: 74,
          4_3: {
            str: "Hello World"
          }
        }
      };

My question is. How do I get the console to say the string?

I have tried something like this:

console.log(obj.obj2[Object.keys(obj.obj2)[2]].str);

But it didn't work.

pilchard
  • 12,414
  • 5
  • 11
  • 23
DaviS
  • 17
  • 3
  • *Why* are you trying to do it this way? In fact, what is the overall goal? [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/q/30076219) explains why `2` is the wrong index here but I really don't see why you'd even want to use an indexed key. – VLAZ Dec 04 '21 at 15:36
  • `console.log(obj.obj2['43'].str);` (which explains why you were using Object.keys to access it, but as VLAZ noted integer keys are sorted before string keys). – pilchard Dec 04 '21 at 15:42
  • To clarify, the underscore is treated as a [numeric seperator](https://v8.dev/features/numeric-separators) so the property is just `43` – pilchard Dec 04 '21 at 15:51

2 Answers2

0

I'm not change the input this time

var obj = {
  prop1: 5,
  obj2: {
    prop1: [3, 6, 3],
    prop2: 74,
    4_3: {
      str: "Hello World"
    }
  }
};

console.log(obj.obj2[Object.keys(obj.obj2)[0]].str);
Fatur
  • 141
  • 9
0

Why not just reference?

var obj = {
        prop1: 5,
        obj2: {
          prop1: [3, 6, 3],
          prop2: 74,
          4_3: {
            str: "Hello World"
          },
        }
      };
      
console.log(obj.obj2['43'].str);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53