遍历仅以特定模式开头的JSON对象 [英] Loop through JSON objects that only start with a certain pattern

查看:83
本文介绍了遍历仅以特定模式开头的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

循环遍历仅以某种特定模式开头的JSON对象的正确/惯用方式是什么?

What is the correct/idiomatic way to loop through JSON objects that only start with a certain pattern?

示例:说我有一个类似JSON的

Example: say I have a JSON like

{
  "END": true, 
  "Lines": "End Reached", 
  "term0": {
    "PrincipalTranslations": {
      // nested data here
    }
  },
  "term1": {
    "PrincipalTranslations": {
      // more nested data here
    }
  }
}

我只想访问PrincipalTranslations对象,并尝试使用:

I only want to access the PrincipalTranslations object and I tried with:

$.each(translations, function(term, value) {
    $.each(term, function(pos, value) {
        console.log(pos);
    });
});

这不起作用,可能是因为我无法遍历ENDLines对象.

Which doesn't work, possibly because I can't loop through the END and Lines objects.

我尝试使用类似的东西

$.each(translations, function(term, value) {
    $.each(TERM-THAT-STARTS-WITH-PATTERN, function(pos, value) {
        console.log(pos);
    });
});

使用通配符,但未成功.我可以尝试弄乱if语句,但是我怀疑还有一个更好的解决方案,我错过了.谢谢.

using wildcards, but without success. I could try to mess up with if statements but I suspect there is a nicer solution I'm missing out on. Thanks.

推荐答案

如果您只对PrincipalTranslations对象感兴趣,则可以使用以下方法:

If you're only interested in the PrincipalTranslations-objects, following would do the trick:

$.each(translations, function(term, value) {
    if (value.PrincipalTranslations !== undefined) {
        console.log(value.PrincipalTranslations);
    }
});

JSFiddle

这篇关于遍历仅以特定模式开头的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆