1

Is it possible to select certain data in a JSON Object using other data in the same JSON Object. Similar to MySQL. For example:

myObj = {"elements" : [ { "name" : "Hydrogen", "symbol" : "H" }, { "name" : "Silver", "symbol" : "Ag" }]};

I want to select "Hydrogen" where the symbol is "H". Instead of having to put in something like this:

document.getElementByID("TEST").innerHTML = myObj.elements[0].name;

Thank you in advance.

1
  • Loop through all elements in the myObj.elements and checks and selects it. Commented Sep 26, 2012 at 3:31

2 Answers 2

1

You could define a function to do it for you.

document.getElementByID("TEST").innerHTML = findNameBySymbol(myObj.elements, 'H');

function findNameBySymbol(elements, symbol) {
  for (var i = 0; i < elements.length; i += 1) {
    if (elements[i].symbol === symbol) {
      return elements[i].name;
    }
  }
}

Better yet, if you have any control over the structure of the data, you could structure it like this:

myObj = {"H": "Hydrogen", "Ag": "Silver"};

Then a lookup is as simple as myObj['H'].

Sign up to request clarification or add additional context in comments.

1 Comment

You are epic dude thanks so much. Sorry bout the dumb question, I just got back into programming/scripting after a 7 month break :/ Thanks again dude!
1

In most cases Tyler Hoilen's solution is good enough. If you have an extremely large data, you can try to convert your data to a hash table, which would provide a fast access to the elements. Just make sure that every element has a unique symbol.

function convertToHash(data) {
  var hash = {};
  for (var i = 0; i < data.length; i++) {
    hash[data[i].symbol] = data[i].name;
  }
  return hash;
}

var hash = convertToHash(myObj.elements);
document.getElementByID("TEST").innerHTML = hash["H"];

Comments

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.