find elements in array
//with array.some
var found = posts.some(el => el.id === id ); // It returns true if id exist in an array
if(found)
{
//Your codes here
}
//with array.filter
var found = posts.filter(el => el.id === id).length > 0; // .length returns 1 if id exist in an array
if(found)
{
//Your code goes here
}
//example to find element
let posts = [ { id: 1, username: 'foo' },{ id: 2, username: 'bar' } ];
let newObj = {"id": 3, "username": 'prasad'};
//console.log(posts);
let found = posts.some(el => el.id === 2 );
if(found)
{
for(num of posts){
//console.log (3, num.id);
if(4 === num.id){
//Your code
//console.log("error");
} else {
//Your code
//console.log(num);
}
};
posts.push(newObj);
console.log(posts);
}