user494461
user494461

Reputation:

how to access individual elements of a javascript object literal?

I have a javascript object literal? I access them in my webpage as data.list[i].ger or data.list[i].eng

If I want to directly search an entry how can I directly access that entry? or do I have to do a linear search or a binary search upon sort?

data = {
    list: [
        {
            "ger": "A-as",
            "eng": "A as"
        },
        {
            "ger": "A-aws",
            "eng": "a-was "
        },
        {
            "ger": "we",
            "eng": "cv"
        },
        {
            "ger": "q",
            "eng": "w-la-w"
        },....

for e.g. if i wanted to access "ger": "q","eng": "w-la-w" I would acces it as data.list[4].ger

is there any way of directly accessing knowing what is the index of that entry?

Upvotes: 0

Views: 890

Answers (2)

Magnar
Magnar

Reputation: 28810

I think you may be looking for JSONSelect. It makes it easy to access data in complex JSON documents, but looks like CSS.

Check out the examples, it looks pretty much like what you want to do.

For instance, to get the eng version of ger:q, you would do .ger:val("q") ~ .eng

You can download it here and use it with JSONSelect.match or JSONSelect.forEach.

Upvotes: 1

brymck
brymck

Reputation: 7663

If you just want to search through your array, I'd go with something like

function lookupTrans(value, fromLang, toLang) {
  for (var i = 0, dataLen = data.list.length; i < dataLen; i++) {
    if (data.list[i][fromLang] === value) {
      return data.list[i][toLang];
      // return i (if you're lookup for just the index number)
    }
  }
  return "";
}

However, I do want to make sure you're not trying to just do one-way internationalization. If that's the case, I'd recommend just using named keys:

var i18n = {
  "translation": {
    "en": "translation",
    "ja": "hon'yaku"
  },
  "list": {
    "en": "list",
    "ja": "risuto"
  },
  "example": {
    "en": "example",
    "ja": "rei"
  },
  "imbueWithConfidence": {
    "en": "Let's translate!",
    "ja": "Hon'yaku shimashou!"
  }
};

Upvotes: 0

Related Questions