How to access elements inside nested objects in a Javascript loop using variable names?

I dont know. I have a JSON string like this one that I need to check for the supplied "property" ( postsome in the following example):

 var index_file = [{ "indexAB":[ { "postsome": ["keyword_abc", "keyword_def"] }, { "testsome": ["keyword_111", "keyword_222"] } ] },{ "index_random": [ { "postsome": ["keyword_abc"] } ] }] 

There will be any number of indexes ("indexAB", "index_random") with n objects inside.

I need to β€œfind” my postsome property, but I cannot get it to work because I am struggling with the correct way to access the object.

So:

 for (var i = 0, l = indices.length; i < l; i += 1) { doc._id = "postsome", index_name = "indexAB"; indices[i]["indexAB"]; // ok, returns object on correct iteration indices[i][index_name]; // undefined indices[i].indexAB[0][doc._id] // ok, returns undefined or keywords indices[i][index_name][0][doc._id] // undefined } 

Question:
How can I access a nested object in a loop using the variable name index_name ?

+4
source share
3 answers

This is not a direct answer to your question, but I believe that it can help you more than give you a sophisticated way to access the values ​​in your object.

If instead of this JSON object:

 var index_file = [{ "indexAB":[ { "postsome": ["keyword_abc", "keyword_def"] }, { "testsome": ["keyword_111", "keyword_222"] } ] },{ "index_random": [ { "postsome": ["keyword_abc"] } ] }]; 

you will have this much simpler data structure:

 var index_file = { "indexAB": { "postsome": ["keyword_abc", "keyword_def"], "testsome": ["keyword_111", "keyword_222"] }, "index_random": { "postsome": ["keyword_abc"] } }; 

then it would be easier using only:

 var value = index_file.indexAB.postsome[0]; // no loops, no nothing // value == "keyword_abc" 

See: DEMO

I think that what you need to change is your data model, because currently it is very far from the idea of ​​JSON, and it will always be very difficult to access data in it.

+2
source

Few problems

  • "indexAB" exists only for the first element of the array
  • you cannot have points inside variable names.

I suggest you check to see if indexAB is a property of an object before setting it aside. See the example below:

Fixed

 var indices = index_file; for (var i = 0, l = indices.length; i < l; i++) { var doc_id = "postsome"; var index_name = "indexAB"; indices[i]["indexAB"]; // ok, returns object on correct iteration indices[i][index_name]; // undefined if ("indexAB" in indices[i]) { indices[i].indexAB[0][doc_id] // ok, returns undefined or keywords indices[i][index_name][0][doc_id] // undefined } } 
+1
source

index_name is undefined because the line before this causes an error

doc._id = "postname" // this causes an error

Just use a simple string

 doc = "postname" 
0
source

All Articles