Loop through JSON objects that only start with a c

2019-09-17 19:52发布

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.

2条回答
Viruses.
2楼-- · 2019-09-17 19:54

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);
查看更多
Fickle 薄情
3楼-- · 2019-09-17 20:17

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

查看更多
登录 后发表回答