简体   繁体   中英

Loop through an object of objects with arrays as values

So I have an object like this:

{
  "apples": [
    "one",
    "two"
  ],
  "oranges": [
    "three",
    "four"
  ]
}

How do I look through this object and find four for example? Something like:

for (var i=0; i < obj.length; i++) {
  for (var y=0; y <obj.childObj.length; y++ {
    obj.childObj[i] === 'four' ? return : null;
  }
}

Or is there a better way to structure this data?

for(var x in obj)
 if(obj.hasOwnProperty(x)) {
  for(var y in obj[x])
   if(obj[x].hasOwnProperty(y)) {
    obj[x][y] === 'four' ? doSomething() : doSomethingElse();
   }
  }

EDIT : Improvement as suggested by Matthew Herbst

You can use for (x in y) statemment:

var data = {
  "apples": [
    "one",
    "two"
  ],
  "oranges": [
    "three",
    "four"
  ]
};

for (var key in data) {
    var obj = data[key];
    for (var i=0; i <obj.length; i++) {
        // obj[i] === 'four' ? return : null;
        console.log(obj[i]);
    }
}

This will print:

one
two
three
four

If you want to find out if this object has four somewhere then

var isFourAvailable = Object.keys(obj).filter(function(val){ return obj[val].indexOf("four") != -1 }).length > 0;

Making it more generic

function findX(x)
{
   return Object.keys(obj).filter(function(val){ return obj[val].indexOf(x) != -1 }).length > 0;
}

Try this ;)

Modified your code;

for (var i = 0; i < obj.length; i++) {
  for (var y = 0; y < obj[i].length; y++ {
    if(obj[i][y] === 'four'){
      console.log("It's four");
    }
  }
}

You can use indexOf

   var x={
      "apples": [
        "one",
        "two"
      ],
      "oranges": [
        "three",
        "four"
      ]
    }
    for (var e in x) {
      if (x[e].indexOf("four") > -1)
        console.log("found Four");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM