Tambo Tambo - 5 months ago 20
JSON Question

How to run a json absolute path in a function

i have a JSON object

stateObj:{
template: {
cache:false,
ref :"templates/pages/menu",
searchability: true,
path: "content.AdminFichiers.aPropos.administrateurs",
lastUpdate: "Dernières mises à jour"
}
}


i call it like this

updatedata (stateObj.template.path);


the function to update the container looks like this

function updatedata (dataObj){
var final = "stateObj",
nameSplit = dataObj.split("."),
uls = document.createElement("ul");

for(i in nameSplit) {
final += '["' + nameSplit[i] +'"]'
}
console.log(final);
for(var i in final){
console.log(stateObj["content"]["AdminFichiers"]["aPropos"]["administrateurs"]);//this shows me the object
console.log(final);//this shows me stateObj["content"]["AdminFichiers"]["aPropos"]["administrateurs"] but i want the object
uls.innerHTML += "<li class='col-3 inline-block card aliceblue fadeIn'><div>Prenom: "+final[i]["prenom"]+"</div><div>Nom: "+final[i]["nom"]+"</div><div>Tel: "+final[i]["tel"]+"</div><div>Mail: "+final[i]["mail"]+"</div><div> Localisation: "+i+"</div></li>"
}
contentElement.appendChild(uls)
}


here is the console.log(final);

stateObj["content"]["AdminFichiers"]["aPropos"]["administrateurs"]


and here is what i get at the end

enter image description here

why am i getting undefine everywhere?

When i do

for(var i in final){console.log(stateObj["content"]["AdminFichiers"]["aPropos"]["administrate‌​urs"]); }


it show me the result as object.

how can i run

stateObj["content"]["AdminFichiers"]["aPropos"]["administrateurs"]


on object

Answer

Your final variable should be an Array of Strings not a String, so you can easily iterate through the words and not waste time splitting strings into arrays.

See the comments in the code below.

function updatedata (dataObj){ 
  var nameSplit = dataObj.split("."),
      uls = document.createElement("ul");

  // Start from the root object, follow each given key
  var final = stateObj;
  for(var i = 0; i < nameSplit.length; ++i) {
    var key = nameSplit [i];
    final = final[key];
  } 

  for(var i in final){
      // This next part is wrong, your final Array is an one dimensional String array
      // Accessing anything in the form of final[i][X] will not yield the result you are looking for
      // What are you trying to output?
       uls.innerHTML +=  "<li class='col-3 inline-block card aliceblue fadeIn'><div>Prenom: "+final[i]["prenom"]+"</div><div>Nom: "+final[i]["nom"]+"</div><div>Tel: "+final[i]["tel"]+"</div><div>Mail: "+final[i]["mail"]+"</div><div> Localisation: "+i+"</div></li>"
  }
     contentElement.appendChild(uls)
}