How to get json objects attribute using javascript

Starts in both JSON and javascript. I need to return the subAttributeOne key from the list of objects instead of its value.

Below is an example of a list,

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

I tried to follow

 list[0].attribute2[1].subAttributeOne 

it returns value , but I need the result of subAttributeOne

+5
source share
2 answers

If you need the keys to an object, you can use object.keys , which will return all the keys, but to determine its position, in your case, you can use, as shown below:

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

But [0] does not work as an index because the order of properties in objects is not a guarantee in JavaScript. To learn more about this, I recommend you read: Is the order for the JavaScript guarantee properties object executed?

In this link you will find the definition of the object from the third release of ECMAScript:

4.3.3 Object

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

+3
source

Wherein:

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

You are getting

 ['subAttributeOne', 'subAttributeTwo'] 
+5
source

All Articles