5

Beginner at both JSON and javascript. I need a way to return the key subAttributeOne it self from a list of object instead of his value.

Following is example of a list,

var list = 
[
   {
   attribute1: "value",
   attribute2:[{subAttributeOne:"value",subAttributeTwo:"value"},{}]
   },
   //other objects
   {..}
]

I have tried following,

list[0].attribute2[1].subAttributeOne

it returns value but the result I need is subAttributeOne

Simo
  • 433
  • 1
  • 6
  • 20
h.alaoui
  • 61
  • 5

2 Answers2

5

With this:

Object.keys(list[0].attribute2[0])

you get

['subAttributeOne', 'subAttributeTwo']
gianlucatursi
  • 660
  • 5
  • 18
3

If you want keys from an object you can use object.keys that will bring back all the keys, but to define its position, in your case you can use like below:

Object.keys(list[0].attribute2[1])[0]

But the [0] doesn't work like an index because properties order in objects is not guarantee in JavaScript. To learn more about this I recommand you to read about : Does JavaScript Guarantee Object Property Order?

In this link you will find the definition of an Object from ECMAScript Third Edition:

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method

Community
  • 1
  • 1
Simo
  • 433
  • 1
  • 6
  • 20