I have a JSON as shown below
[
{
"name": "Mike",
"incentives": "23.45",
"id": "1"
},
{
"name": "Larsen",
"incentives": "34.78",
"id": "2"
},
{
"name": "Steve",
"incentives": "26.78",
"id": "3"
}
]
I need to push a new JSON Object into the JSON array if id not exists inside the JSON Object
tried as this way and working , any better way of doing this
$(document).ready(function() {
var idsarray = [];
var test = [
{
"name": "Mike",
"incentives": "23.45",
"id": "1"
},
{
"name": "Larsen",
"incentives": "34.78",
"id": "2"
},
{
"name": "Steve",
"incentives": "26.78",
"id": "3"
}
];
for(var i=0;i<test.length;i++)
{
idsarray.push(test[i].id)
}
var newobj = {
"name": "RAM",
"incentives": "56.78",
"id": "4"
}
var newid = newobj.id;
if(jQuery.inArray(newid, idsarray) !== -1)
{
test.push(newobj)
}
alert(test.length)
});
idsarraywith new element added