Adding/removing items from a JavaScript object with jQuery
First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.
Your code defines an object (data
) containing an array (items
) of objects (each with an id
, name
, and type
).
You don't need or want jQuery for this, just JavaScript.
Adding an item:
data.items.push(
{id: "7", name: "Douglas Adams", type: "comedy"}
);
That adds to the end. See below for adding in the middle.
Removing an item:
There are several ways. The splice
method is the most versatile:
data.items.splice(1, 3); // Removes three items starting with the 2nd,
// ("Witches of Eastwick", "X-Men", "Ordinary People")
splice
modifies the original array, and returns an array of the items you removed.
Adding in the middle:
splice
actually does both adding and removing. The signature of the splice
method is:
removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
index
- the index at which to start making changesnum_to_remove
- starting with that index, remove this many entriesaddN
- ...and then insert these elements
So I can add an item in the 3rd position like this:
data.items.splice(2, 0,
{id: "7", name: "Douglas Adams", type: "comedy"}
);
What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:
var data = {items: [
{id: "1", name: "Snatch", type: "crime"},
{id: "2", name: "Witches of Eastwick", type: "comedy"},
{id: "7", name: "Douglas Adams", type: "comedy"}, // <== The new item
{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"}
]};
You can remove some and add some at once:
data.items.splice(1, 3,
{id: "7", name: "Douglas Adams", type: "comedy"},
{id: "8", name: "Dick Francis", type: "mystery"}
);
...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:
var data = {items: [
{id: "1", name: "Snatch", type: "crime"},
{id: "7", name: "Douglas Adams", type: "comedy"},
{id: "8", name: "Dick Francis", type: "mystery"},
{id: "4", name: "Ordinary People", type: "drama"},
{id: "5", name: "Billy Elliot", type: "drama"},
{id: "6", name: "Toy Story", type: "children"}
]};
Remove element from object jquery
The Object.keys()
will give you in the order of how it is defined. Always it is better to remove based on the key name. Because, in an object, the keys are not exactly sorted and they don't have any order.
var obj = { duur: ".short", taal: ".nl", topic: ".algemeen-management"};console.log(obj);var position = 2;delete obj[Object.keys(obj)[position - 1]];console.log(obj);
A view to add and remove items from a collection on the same view
Having a single 'remove' button does not make sense and you need a 'remove' associated with each item in the collection. In addition, remove the id
attributes from your <div>
elements and use relative selectors.
Change the partial to
@using (Html.BeginCollectionItem("recipients"))
{
<div class="item" data-id="@Model.ID"> // add an enclosing element
@Html.HiddenFor(m => m.ID)
@Html.LabelFor(m => m.Recipient)
@Html.TextBoxFor(m => m.Recipient)
@Html.ValidationMessageFor(m => m.Recipient)
@Html.LabelFor(m => m.Amount)
@Html.TextBoxFor(m => m.Amount)
@Html.ValidationMessageFor(m => m.Amount)
<button type="button" class="remove">Remove</button> // add button
</div>
}
The in the main view, your scripts will be
var url = '@Url.Action("Recipient")';
var recipients = $('#recipients');
$('#add').click(function () {
$.get(url, function (response) {
recipients.append(response);
});
});
$('#recipients').on('click', '.remove', (function() {
var container = $(this).closest('.item');
var id = container.data('id');
if (!id) {
container.remove();
} else {
// see notes below
}
}
For any items that have been added in the view, the value of property ID
will be null
and the code in the if
block will remove the item from the view. However for existing items that you may be editing (where the ID
has a value), then you need to consider how to remove it from the database. Options include
Adding an additional property in the view model (say)
public bool
and including a hidden input in the partial
IsDeleted { get; set; }
for it. You could then set it totrue
so when you submit, you can
delete allrecipients.Where(x => x.IsDeleted);
@Html.HiddenFor(m => m.IsDeleted, new { @class = "flag" })
} else {
container.find('.flag').val('true');
}Making an ajax call to a server method which deletes the item from
the database, and if successful, remove the associated container
from the DOM} else {
$.post(yourDeleteUrl, { id: id }, function(response) {
if(response) {
container.remove()
} else {
// oops, something went wrong
}
});
}
Find and remove objects in an array based on a key value in JavaScript
I can grep the array for the id, but how can I delete the entire object where id == 88
Simply filter by the opposite predicate:
var data = $.grep(data, function(e){
return e.id != id;
});
jQuery/JS: delete object from array and DOM
BUG1:
You can't fire on click
function on dynamically generated DOM element like that.
Add event listener to your element (using pure JS):
elem.addEventListener("click", func, false);
Or change syntax of your click function to this (using jQuery):
$(document).on("click",'.delete-contact', (event) => {
// your code here
});
BUG2:
I don't know why this function acts like that, but you always have to pass default string parameter. Look to the next lines I made:
let html = arr.reduce((all, one) => all += one.toHTML(), '');
Working fiddle
How to remove object from arrayList using javascript or jquery?
var newData = { "docId":2, "letterNo":1, "seqNo":1};//Solution using filtersvar insertNewData = false;var imageList = [{ "docId":1, "letterNo":1, "seqNo":1},{ "docId":2, "letterNo":1, "seqNo":1},{ "docId":3, "letterNo":1, "seqNo":1}];imageList = imageList.filter(function(oldData){ if(oldData["docId"] == newData["docId"] && oldData["letterNo"] == newData["letterNo"] && oldData["seqNo"] == newData["seqNo"]) { insertNewData = true;//a flag return false;//remove old data from array } else return true;});if(insertNewData){ imageList.push(newData); insertNewData = false; console.log("old data is removed and new data is pushed using filters",imageList);}
Related Topics
Wkwebview - Complex Communication Between JavaScript & Native Code
Template Language That Works on Both Server and Client
Time Conversion Between Ruby on Rails and JavaScript Vice Versa
Fire Greasemonkey Script on Ajax Request
Sort an Array of Object by a Property (With Custom Order, Not Alphabetically)
Rails 5 - Turbolinks 5,Some Js Not Loaded on Page Render
Javascriptcore Call Function with Callback Swift
Browser-Independent Way to Detect When Image Has Been Loaded
React - User-Defined Jsx Components Not Rendering
How to Use JavaScript in Ruby on Rails
How to Count the Number of Occurrences of Each Item in an Array
Resize Svg When Window Is Resized in D3.Js
Rails Specify Load Order of JavaScript Files
How to Linebreak an Svg Text Within JavaScript
JavaScript Code Trick: What's the Value of Foo.X
Is There an Internet Explorer Approved Substitute for Selectionstart and Selectionend