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!"
}
]