[英]Handlebarsjs Array of Objects: TypeError: Cannot read property 'id' of undefined
[英]array of objects: Cannot read property 'id' of undefined inside onchange event
我一直在尋找一種方法,如果id變量等於對象的id,則從對象數組中刪除單個對象。
我使用數組來知道選中了哪些復選框,以便收集相關信息以進行進一步處理。
示例: https : //jsbin.com/vicerewevi/edit?html,js,輸出
快速選擇復選框時出現的錯誤:
Uncaught TypeError: Cannot read property 'id' of undefined
at vicerewevi.js:33
at Function.each (jquery-3.1.0.js:368)
at HTMLInputElement.<anonymous> (vicerewevi.js:32)
at HTMLInputElement.dispatch (jquery-3.1.0.js:5110)
at HTMLInputElement.elemData.handle (jquery-3.1.0.js:4918)
如果value.id == id,則在行上發生上述錯誤:
// if checkbox is checked, add object to array and if unchecked remove object by 'id' from array
$('.checkbox').change( function(){
var id = parseInt($(this).attr('data-id'))
var foo = $(this).parent().siblings().find('#foo').val()
var bar = $(this).parent().siblings().find('#bar').val()
if($(this).prop('checked')) {
var obj = {'id': id, 'foo': foo, 'bar': bar}
jsonobjects.push(obj)
} else {
$.each(jsonobjects, function( index, value ) {
if (value.id == id ) {
jsonobjects.delete(index)
}
});
}
countChecked() // update count of checkboxes
console.log(JSON.stringify(jsonobjects))
$('#output').html(JSON.stringify(jsonobjects, null, ""))
});
我在下面嘗試的SO上找到了以下代碼(以前從未使用過自定義原型):
Array.prototype.delete = function(pos){
this[pos] = undefined;
var len = this.length - 1;
for(var a = pos;a < this.length - 1;a++){
this[a] = this[a+1];
}
this.pop();
}
因為您從數組中delete
條目,所以下次您對其進行迭代時,您將獲得一個undefined
的value
,該value
針對數組中的特定“間隙”。 顯然,這沒有id
屬性。
要解決此問題,請不要使用delete
,而要使用filter
創建一個新的,經過過濾的數組,該數組將不會出現這種間隙。
更換:
$.each(jsonobjects, function( index, value ) {
if (value.id == id ) {
jsonobjects.delete(index)
}
});
...具有:
jsonobjects = jsonobjects.filter(function( value ) {
return value.id !== id;
});
或者,如果您想堅持使用jQuery方法,請使用$.grep
:
jsonobjects = $.grep(jsonobjects, function( value ) {
return value.id !== id;
});
我一直在尋找一種方法,如果id變量等於對象的id,則從對象數組中刪除單個對象。
const arr = [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 } ]; const removeById = (arr, id) => arr.filter(e => e.id !== id); const no2 = removeById(arr, 2); const no5 = removeById(arr, 5); console.log(no2); console.log(no5);
利用Array.filter
方法並將jsonobjects
重新分配給過濾后的數組,就像這樣,而不是您創建的delete方法
jsonObjects = jsonObjects.filter((value, index) => { return value.id !== id; })
我希望這會jsonObjects = jsonObjects.filter((value, index) => { return value.id !== id; })
幫助
當我嘗試在該awnser For..In JavaScript中的循環中解決方案時,這對我有用-鍵值對
for (var k in jsonobjects){
if (jsonobjects.hasOwnProperty(k)) {
if (jsonobjects[k].id == id) {
jsonobjects.splice(k, 1)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.