从数组中删除JSON对象会创建“undefined”对象 [英] Deleteing JSON object from an array creates "undefined" objects

查看:215
本文介绍了从数组中删除JSON对象会创建“undefined”对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了JSON和数组的一些问题。我一直在搞乱JSON一段时间,并试图通过重构旧的实现来使用生产中的一些。我有两个隐藏的文本域,一个商店ID格式[1] [2] [3]等,另一个名称[name1] [name2] [name3]所以我认为这将是一个很好的练习,以了解更多关于JSON和重构,并使用更可读的对象表示法。

i am haveing some problems with JSON and arrays. I have been messing around with JSON for a little while and am trying to use some in production by refactoring a old implementation. What i had was two hidden textfields, one store ids in the format [1][2][3] etc and the other name [name1][name2][name3] so i thought this would be a great excercise to learn more about JSON and refactor that out and use a more readable object notation.

无论如何我离题了。我遇到的问题很有趣,我发现如何将JSON推到一个数组中,但问题出在我的删除方法中。当我从数组中删除一个对象时,逗号仍然存在,创建未定义对象。我做错了吗,还有更好的方法吗?

Anyway i digress. The problem i am having is a funny one, i found out how to "push" JSON into an array, but the problem comes in my delete method. When i delete an object out of the array the commas persist, creating "undefined" objects. Am i doing this wrong, and is there a better way?

在阵列中添加了2项(一切正常)

[{id:"1", name:"Test (ID: 1)", status:"new"}, {id:"2", name:"Test 2 (ID: 2)", status:"new"}]

从数组中移除1项(逗号留在)

[{id:"1", name:"Test (ID: 1)", status:"new"}, ,]

在数组中添加了另一个项目,逗号现在导致undefined 对象

[{id:"1", name:"Test (ID: 1)", status:"new"}, , {id:"2", name:"Test 2 (ID: 2)", status:"new"}]

这是我的删除功能

    function removeFromList(Id) {
    var txtIDs = $("#<%= selected.ClientID %>");
    var data = eval(txtIDs.val());

    for (var i = 0; i < data.length; i++) {
        alert(typeof (data[i]));
        if (typeof(data[i]) != 'undefined') {
            if (data[i].id == Id)
                delete data[i]; // alert(data[i].name); //  
        }
    }     
}

感谢您查看这对我来说:)

Thanks for looking at this for me :)

Rob

推荐答案

删除是一个运算符用于从对象中删除键 - 您不应该真正使用它来从数组中删除项目,因为它不会按预期执行。您可以使用splice或slice等数组方法来操作数组。

Delete is an operator used to delete keys from objects - you shouldn't really use it to remove items from an Array because it won't do what you expect. You can use Array methods like splice or slice to manipulate the array.

MDC数组方法文档将有所帮助:)

或者,您可以使用类似的函数这个:

Alternatively, you could use a function like this:

function removeArrayEl(arr, index){
    newArr = [];
    for(var i = 0, l = arr.length;i < l; i++){
        if(i != index){
            newArr.push(arr[i]);
        }
    }
    return newArr;
}






[edit]
正如评论者指出的那样,Array splice方法正是这项工作的正确工具,但我将保留该函数以供参考。
[/ edit]


[edit] As the commenters have pointed out, the Array splice method is exactly the right tool for this job, but I'll leave the function for reference. [/edit]

这篇关于从数组中删除JSON对象会创建“undefined”对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆