Loop through JSON objects that only start with a certain pattern

五迷三道 提交于 2019-12-25 05:50:43

问题


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

Example: say I have a JSON like

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

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);
    });
});

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

I tried to go with something like

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

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.


回答1:


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




回答2:


How I would search for a property in an object it is like this:

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);


来源:https://stackoverflow.com/questions/23998293/loop-through-json-objects-that-only-start-with-a-certain-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!