user2227400
user2227400

Reputation:

Query a nested JSON Object/Array with underscore

Assumed that is the JSON structure:

var myData = [
  {
    "id": 68,
    "country": "US",
  },
  {
    "id": 82,
    "country": "PL",
  },
  {
    "id": 83,
    "country": "US",
  }
];

I want to get all items, where country == US

Following try does not work:

var myResult = _.where (myData, {'country': 'US'});

I get an empty result > myResult []

What is the mistake?

EDIT: Sorry, the use of lodash and underscore together was the problem !

Upvotes: 0

Views: 1113

Answers (1)

JCarlosR
JCarlosR

Reputation: 1664

I never used underscore.js before, but I have tried your code and it works totally.

Please make sure that you are importing the library.

I have used the next code in the body tag of an empty HTML file:

<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
    var myData = [
      {
        "id": 68,
        "country": "US",
      },
      {
        "id": 82,
        "country": "PL",
      },
      {
        "id": 83,
        "country": "US",
      }
    ];

    var myResult = _.where (myData, {'country': 'US'});
    console.log(myResult);
</script>

And the result is:

Console result

Upvotes: 2

Related Questions