Skip to content Skip to sidebar Skip to footer

How To Find Specific Objects And Put Them In An Array In Javascript

I have this result in my script '[{'region':'NCA','depprt':'Havana, Cuba'},{'region':'NCA','depprt':'Havana, Cuba'},{'region':'NCA','depprt':'Montego Bay, Jamaica'},{'region':'NCA'

Solution 1:

You can use the .filter() method for this.

var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });

Solution 2:

Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.

var filtered = [];
jList.forEach(function(item) {
   if(item.region == 'NCA') {
      filtered.push(item);
   }
});

Solution 3:

Just iterate over it:

var filteredDepprts = [];
jsList.forEach(function(element){
  if(element.region == 'NCA'){
    filteredList.push(element.depprt); //or element if you want to push the full object
  }
});

Solution 4:

The JSON.stringify method converts a JavaScript value to a string.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

When you want to convert a JSON string to a JavaScript value, use JSON.parse

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

var jsonList = '@Html.Raw(Json.Encode(ViewBag.chk))'var jsList = JSON.parse(jsonList);

Using single quotes around your @Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings

Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Solution 5:

Try map:

var obj= [];
for (i in jsonList) {
  if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}

https://jsfiddle.net/pd6hvn78/

Post a Comment for "How To Find Specific Objects And Put Them In An Array In Javascript"