不使用删除从对象列表中取消?

时间:2012-03-15 19:07:36

标签: javascript arrays list object

如果我可以使用list[value][index]从对象访问对象,如何在不使用list的情况下从delete删除或取消该对象? (因为在对象列表中不可能)

我的对象如下:

var list = {
    'test1': [
        {
            example1: 'hello1'
        },
        {
            example2: 'world1'
        }
    ]
    'test2': [
        {
            example1: 'hello2'
        },
        {
            example2: 'world2'
        }
    ]
};

删除对象后,我希望它看起来像这样:

var list = {
    'test1': [
        {
            example1: 'hello1'
        }
    ]
    'test2': [
        {
            example1: 'hello2'
        },
        {
            example2: 'world2'
        }
    ]
};

当我使用删除时,它看起来像这样:

var list = {
    'test1': [
        {
            example1: 'hello1'
        },
        null
    ]
    'test2': [
        {
            example1: 'hello2'
        },
        {
            example2: 'world2'
        }
    ]
};

3 个答案:

答案 0 :(得分:1)

您可以将list的值设置为list[key],从undefined中删除该对象。但是,这不会删除密钥 - 您需要delete来执行此操作:

list['test1'] = undefined; // list is now { test1: undefined, test2: [ ... ]}
delete list['test1']; // list is now { test2: [ ... ] }

您是否有特殊原因想要使用delete?如果您只是检查list['test1']的真实性(例如if (list['test1']) ...),但是如果您想使用list或类似的东西来迭代for (var key in list),那么这将无济于事那,delete是一个更好的选择。

编辑:好的,看起来您的实际问题是“如何从数组中删除值?”,因为这就是您正在做的事情 - 您的阵列位于对象,或包含对象而不是其他值,是无关紧要的。为此,请使用splice()方法:

list.test1.splice(1,1); // list.test1 has been modified in-place

答案 1 :(得分:0)

(改写为更正的问题。)

你可以写:

list[value].splice(index, 1);

删除list[value][index],从而将数组缩短一个。 (以上“替换”1元素,从位置index开始,没有元素;有关该方法的一般文档,请参阅splice in MDN。)

答案 2 :(得分:0)

以下是使用splice的示例:

http://jsfiddle.net/hellslam/SeW3d/