Thursday, March 8, 2018

find an item in a collection within a collection with a .some inside a .some

let id = 7;
let match = null;
let foo = {
   bar: [
      {
         baz: [
            {
               qux: 1,
               color: "red"
            },
            {
               qux: 2,
               color: "green"
            },
            {
               qux: 3,
               color: "blue"
            }
         ]
      },
      {
         baz: [
            {
               qux: 4,
               color: "cyan"
            },
            {
               qux: 5,
               color: "magenta"
            },
            {
               qux: 6,
               color: "yellow"
            },
            {
               qux: 7,
               color: "black"
            }
         ]
      },
      {
         baz: [
            {
               qux: 8,
               color: "plaid"
            },
            {
               qux: 9,
               color: "paisley"
            }
         ]
      }
   ]
}
foo.bar.some(x => x.baz.some(y => {
   if (y.qux === id) {
      match = y;
      return true;
   }
   return false;
}));
alert(match.qux + " - " + match.color);

No comments:

Post a Comment