开发者

how to access individual elements of a javascript object literal?

I have a javascript object literal? I access the开发者_开发知识库m 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?


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.


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!"
  }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜