ProMike360 ProMike360 - 27 days ago 13
JSON Question

jQuery search in an object using a string

I want to search in a object using a string.

Example:



JSON

{
"nl": {
"lang":"Nederlands",
"header-WelcomeText":"Welkom op de website",
"header-Sub1":"Hoofdpaneel"
},
"en": {
"lang":"English",
"header-WelcomeText":"Welcome on the website",
"header-Sub1":"Dashboard"
}
}


Javascript/jQuery

var output;
$.get("file.json", function(response){
output = response; //This is now a object in javascript
});


This all works, here what i want:

//The jQuery code
$('span .lang').text(output.nl.$(this).attr("data-lang"));

//The HTML code
<span class="lang" data-lang="header-Sub1"></span>


I know this will not work, but I know there will be a way to achief this.

Answer

To make this work there's a few changes you need to make.

  • when accessing the key of an object through a variable you need to use bracket notation.
  • to reference the element through the this keyword you need to run your code within it's scope. To do that you can pass a function to the text() method which returns the value you need from the object.
  • the .lang class is directly on the span, so you shouldn't have the space in your selector.

With all that in mind, this should work for you:

var output = {
  "nl": {
    "lang": "Nederlands",
    "header-WelcomeText": "Welkom op de website",
    "header-Sub1": "Hoofdpaneel"
  },
  "en": {
    "lang": "English",
    "header-WelcomeText": "Welcome on the website",
    "header-Sub1": "Dashboard"
  }
}

$('span.lang').text(function() {
  return output.nl[$(this).data("lang")];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="lang" data-lang="header-Sub1"></span>