-2

I want to loop through a dynamic object, match the value, if item matched, jump out of the loop...

Let say have an object:{a:false:b:true,c:false} I want to do something like (with loadash),

_.fowOwn({a:1,b:2}, function (value, key) {
  console.log(key);
  if(value); break;
});

So this should log (a & b). How can I break when the item is matched ?

Thanks for any help.

Fahad Khan
  • 1,635
  • 4
  • 23
  • 37
  • Use `_.find()`? – VLAZ Oct 28 '16 at 10:06
  • `So this should log (a & b)` - no, it shouldn't. Objects have no ordering, so iteration order is unspecified. Most browsers tend to keep it consistent but you shouldn't rely on it. – VLAZ Oct 28 '16 at 10:09
  • [short circuit loob](http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break). :) –  Oct 28 '16 at 10:09
  • @viaz the order doesn't matter in the real scenario, the purpose is to break when the condition is met. – Fahad Khan Oct 28 '16 at 10:11
  • @TooNDinDarkDevil Thanks, let me try – Fahad Khan Oct 28 '16 at 10:13
  • 2
    @Fahad Well, I wanted to make sure you weren't going in with the wrong assumption as _relying_ on iteration order of objects is both wrong and dangerous. Also wide-spread. At any rate, why not use `find`? It is exactly what you want, isn't it? – VLAZ Oct 28 '16 at 10:13
  • @vlaz yes, `_.find` looks good, giving a hand on it – Fahad Khan Oct 28 '16 at 10:15
  • Thanks @vlaz, done it with `_.find` – Fahad Khan Oct 28 '16 at 10:28

1 Answers1

0

$.grep in jquery is the solution. Example :

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rajesh Grandhi
  • 378
  • 3
  • 13
  • I was looking for the solution with loadash or pure javascript. – Fahad Khan Oct 28 '16 at 10:19
  • 1
    `$.grep` is doubly unneeded with that example, as you can simply do `data.items.find(function(item) { return item.id===1} )`, there is no need for jQuery. – VLAZ Oct 28 '16 at 10:28