jquery - remove array element using javascript -
i new javascript & jquery, need remove element below array structure
[{ "tag": "tag1", "description": "description1" }, { "tag": "tag2", "description": "description2" }, { "tag": "tag3", "description": "description3" }] the element removed known {"tag":"tag2", "description":"description2"}.
how can find element , remove array.
please find code using remove element
var actiondic = []; actiondic.push({ description: desc, tag: tag }); the actiondic array populated user come in text in textinput , selects 'add' option.
var deleterow = { tag: "tag2", description: "description2" }; var index = $.inarray(deleterow, actiondic); if (index != -1) { actiondic.splice(index, 1); } the right index not obtained. kindly allow me know wrong in code.
thanks.
since comparing between item remove , each element in actiondic isn't trivial, utilize jquery.grep():
actiondic = jquery.grep(actiondic, function(elem) { homecoming elem.tag == deleterow.tag && elem.description == deleterow.description; }, true); demo
it performs search using custom search function , returns array elements didn't match. result replaces previous value of actiondic , removed 1 item.
unfortunately, method considered heavy because new array gets created @ each invocation; both in terms of jquery can , standard javascript functionality, particular feature lacking. ecmascript 6 have array.prototype.find() method job of finding index in array (with can perform splice).
you can of course of study write 1 too:
(function($) { $.find = function(arr, fn) { (var = 0, len = arr.length; < len; ++i) { if (fn(arr[i], i, arr)) { homecoming i; } } homecoming -1; }; }(jquery)); var index = $.find(actiondic, function(elem) { homecoming elem.tag == deleterow.tag && elem.description == deleterow.description; }); if (index != -1) { actiondic.splice(index, 1); } demo
javascript jquery arrays
No comments:
Post a Comment