0

How do I get the property value of name of this object's 2nd child?

var obj = {
    'one_child': {
        name: 'a',
        date: '10'
    },
    'two_child': {
        name: 'b',
        date: '20'
    }
}

I've tried Object.keys(obj)[1].name, but doesnt work.

gespinha
  • 7,968
  • 16
  • 57
  • 91
  • 3
    There is no "first" and "second" with object properties - there's no defined ordering. You can use `Object.keys()` to get an array of property names, but there's no guarantee that it will return the keys in any particular order. – Pointy Aug 19 '15 at 15:31
  • @Pointy: Since ES6 non-numeric properties (property names) are iterated over in insertion order. And that's what at least Chrome and Firefox have implemented for a while. (I still think one should use an array if order is required). – Felix Kling Aug 19 '15 at 15:32
  • Object.keys returns an array of keys, not the object as an array. You want, `obj[Object.keys(obj)[1]].name`. – Dave Chen Aug 19 '15 at 15:32
  • `Object.keys` returns the *keys* (`one_child`, `two_child`), not the *values* in the object?! – Bergi Aug 19 '15 at 15:34
  • @FelixKling: Exactly, there's a guarantee now, but it still shouldn't be used… So let's not advocate it :-) – Bergi Aug 19 '15 at 15:36
  • There's no guarantee that future versions won't break this. Also not all browsers are following this either. If it's not in the spec, don't depend on it. If you need ordering, add an property to specify order, you can even just sort your date property. [Clicky](https://code.google.com/p/v8/issues/detail?id=164) – Dave Chen Aug 19 '15 at 15:40
  • @DaveChen: Well, it *is* in the spec. http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys – Felix Kling Aug 19 '15 at 15:42
  • @FelixKling You're right! This seems like a pretty active issue, with a project member [stating that it is in violation of the spec](https://code.google.com/p/v8/issues/detail?id=3056). I guess you could say don't rely on specs that are too new to be implemented. (Like the latest html5 goodies) – Dave Chen Aug 19 '15 at 15:47
  • @FelixKling well, I wouldn't say that was a "guarantee"; two objects with the same set of properties and values can still have differing property name ordering. – Pointy Aug 19 '15 at 15:47

1 Answers1

1

You define an object with properties, so you can access it directly using :

obj.two_child.name
alexbchr
  • 603
  • 4
  • 14