Remove json element
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
You can try to delete the JSON as follows:
var bleh = {first: '1', second: '2', third:'3'}
alert(bleh.first);
delete bleh.first;
alert(bleh.first);
Alternatively, you can also pass in the index to delete an attribute:
delete bleh[1];
However, to understand some of the repercussions of using deletes, have a look here
For those of you who came here looking for how to remove an object from an array based on object value:
let users = [{name: "Ben"},{name: "Tim"},{name: "Harry"}];
let usersWithoutTim = users.filter(user => user.name !== "Tim");
// The old fashioned way:
for (let [i, user] of users.entries()) {
if (user.name === "Tim") {
users.splice(i, 1); // Tim is now removed from "users"
}
}
Note: These functions will remove all users named Tim from the array.
Do NOT have trailing commas in your OBJECT (JSON is a string notation)
UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing
var data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.
data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.