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

2
  • 1
    Err… You already know you're looking for the string "subAttributeOne"… so what's there to look up in the array? It's not very clear what you're trying to accomplish. Commented Aug 24, 2016 at 8:56
  • USE Object.keys(list[0].attribute2[0]); Commented Aug 24, 2016 at 9:00

2 Answers 2

5

With this:

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

you get

['subAttributeOne', 'subAttributeTwo']
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

This working only because subAttributeTwo is bigger then subAttributeOne. The order of the keys is alphabetically
@t.gian18 The order is arbitrary, i.e. there is none.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.