Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use conditional inside $.each function to create array

I want to iterate over the elements of an array and if a condition is true I want to create a new array.

Example: I have an array called Messages whose elements are objects and I want to check if the id attribute equals 5. If yes create a new array only consisting of this object.

messages = [{
  "id": 10,
  "body": "hello!"
}, {
  "id": 21,
  "body": "hola!"
}, {
  "id": 5,
  "body": "ciao!"
}];

var message5 = [];
var dataObj = {};

$.each(messages, function(index, value) {
  if (value.id == 5) {
    dataObj[index] = value;
  }
});

message5.push(dataObj[index]);

I want my result to be:

message5 = [
 {
  "id": 5,
  "body": "ciao!"
 }
]    
like image 413
Dimitrios Vythoulkas Avatar asked Mar 10 '16 13:03

Dimitrios Vythoulkas


3 Answers

Try to use Array.prototype.filter at this context,

var message5 = messages.filter(function(itm){
  return itm.id == 5;
});

console.log(message5);  //[{"id": 5,"body": "ciao!"}] 

If you want it to be more concise then you could use ES6 Arrow function,

var message5 = messages.filter(itm => itm.id == 5);
console.log(message5);  //[{"id": 5,"body": "ciao!"}]

But note that, the above code is similar to,

var message5 = messages.filter(function(itm){
  return itm.id == 5;
}.bind(this)); //Arrow function will automatically bind its lexical scope to it.
like image 139
Rajaprabhu Aravindasamy Avatar answered Sep 26 '22 02:09

Rajaprabhu Aravindasamy


try to use filter:

var messages = [{
  "id": 10,
  "body": "hello!"
}, {
  "id": 21,
  "body": "holla!"
}, {
  "id": 5,
  "body": "ciao!"
}];
var message5 = messages.filter(function(message) {
  return message.id == 5;
});
alert(JSON.stringify(message5));
like image 27
jcubic Avatar answered Sep 23 '22 02:09

jcubic


try

var newArr = messages.filter( function(value){

   return value.id == 5;

} );
like image 23
gurvinder372 Avatar answered Sep 25 '22 02:09

gurvinder372