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!"
}
]
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.
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));
try
var newArr = messages.filter( function(value){
return value.id == 5;
} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With