循环只以特定模式开始的JSON对象

Loop through JSON objects that only start with a certain pattern

本文关键字:开始 JSON 对象 模式 循环      更新时间:2023-09-26

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

示例:假设我有一个JSON,如

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

我只想访问PrincipalTranslations对象,我尝试了:

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

这不起作用,可能是因为我不能循环通过ENDLines对象。

我试着用一些像

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

使用通配符,但没有成功。我可以尝试用if语句搞砸,但我怀疑有一个更好的解决方案,我错过了。谢谢。

如果您只对PrincipalTranslations -对象感兴趣,下面的代码可以满足您的需求:

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

JSFiddle

如何在对象中搜索属性它是这样的

var obj1 ={ /* your posted object*/};

// navigates through all properties
var x = Object.keys(obj1).reduce(function(arr,prop){
// filter only those that are objects and has a property named "PrincipalTranslations"
    if(typeof obj1[prop]==="object" &&  Object.keys(obj1[prop])
        .filter(
            function (p) {
                return p === "PrincipalTranslations";})) {
                     arr.push(obj1[prop]);
                }
    return arr;
},[]);
console.log(x);