var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
Answer from dteoh on Stack Overflowvar json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an 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.
Run code snippetEdit code snippet Hide Results Copy to answer Expand
javascript - Remove Json object from json array element - Stack Overflow
javascript - Delete data from json array - Stack Overflow
javascript - Search and remove object from json array - Stack Overflow
Total noob: how to remove an element from a JSON array
// Assuming this is your fetched data
const fetchMethodJsonArray = [{
"val": "One"
}, {
"val": "Two"
}, {
"val": "Three"
}];
var setValue = fetchMethodJsonArray;
const dataRemoved = setValue.filter((el) => {
return el.val !== "One";
});
console.log(dataRemoved);
Answer from what i got..
jsonArray.splice(jsonArray.indexOf('string_to_search'));
It will delete the found item and return remaining array.
To unset any variable use the delete statement:
delete favorites.favorites[1].items[1]
This is correct way, and it will work, but if your goal is to preserve indexes in order, then your way with the splice method is the way to go:
favorites.favorites[1].items.splice(1,1);
The above will remove one element (second parameter) starting at 1st index (first parameter).
So to be clear: to remove the last element use this:
var arr = favorites.favorites[1].items;
arr.splice(arr.length - 1, 1);
See your code on JsFiddle.
You can take additional measures to protect the code in case the array is not set or empty:
var arr = favorites.favorites[1].items;
if ( arr && arr.length ) {
arr.splice(arr.length - 1, 1);
}
If you want to actually remove an item from the array so that all items after it in the array move down to lower indexes, you would use something like this:
favorites.favorites[1].items.splice(1, 1);
You want to operate on the actual items array which means calling methods on the items array. For .splice(), you pass the index where you want to start modifying the array and then the number of items to remove thus .splice(1, 1) which will remove 1 item starting at index 1.
You're using not valid data structure, your array needs to be in square brackets []
For your case better to use filter function:
var data = [
{id: "1", name: "Snatch", type: "crime"},
{id: "2", name: "Witches of Eastwick", type: "comedy"},
{id: "3", name: "X-Men", type: "action"},
{id: "4", name: "Ordinary People", type: "drama"},
{id: "5", name: "Billy Elliot", type: "drama"},
{id: "6", name: "Toy Story", type: "children"}
];
function RemoveNode(id) {
return data.filter(function(emp) {
if (emp.id == id) {
return false;
}
return true;
});
}
var newData = RemoveNode("1");
document.write(JSON.stringify(newData, 0, 4));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
A better way might be to filter your original array to remove the item you dont want.
Assuming data is really an array of objects (ie, does not have the error currently in your question)
function RemoveNode(id){
return data.filter(function(e){
return e.id !== id;
});
}
You could also use splice, however that would require knowing the index of the item you want to remove, and by the time you've found that you may as well just filter!
I am using an API tool that allows for simple vanilla JS functions. I’ve been trying to figure out how to remove an element from an Array all day, but I feel like I’m missing something in the vernacular as I can’t find any solid examples online, but feel like this is a fairly common thing.
I have data in this exact format (I know it’s not technically valid JSON, but it’s what will be used to form the proper JSON):
[ { "url": "http://google.com", "text": { "text": "T123123123", "type": "plain_text" }, "type": "button", "value": "postback_1" }, { "url": "http://google.com", "text": { "type": "plain_text" }, "type": "button", "value": "postback_2" } ]
I need to remove all elements that have a missing text.text
This example has 2 elements, but it could be up to 10 total, with 2-3 needing to be removed. The API I’m working with cannot handle empty structures, so I need to remove them when the data passed into the structure is missing.
Any help?!
Created a handy function for this..
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
array.splice(index, 1);
}
});
}
//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
countries.results.removeValue('name', 'Albania');
To iterate through the keys of an object, use a for .. in loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
- https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete
JSfiddle
function deleteEmpty(obj){
for(var k in obj)
if(k == "children"){
if(obj[k]){
deleteEmpty(obj[k]);
}else{
delete obj.children;
}
}
}
for(var i=0; i< a.children.length; i++){
deleteEmpty(a.children[i])
}