简体   繁体   中英

Unshift from object list without using delete?

If I can access an object from an object using list[value][index] , how can I delete or unshift that object from list without using delete ? (since that isn't possible in an object list)

My object looks like this:

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

After deleting an object, I want it to look like this:

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

When I use delete, it looks like this:

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

You can remove the object from list by setting the value of list[key] to undefined . This won't remove the key, however - you'd need delete to do that:

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

Is there a particular reason you don't want to use delete ? It won't make a difference if you're just checking list['test1'] for truthiness (eg if (list['test1']) ... ), but if you want to iterate through list using for (var key in list) or something like that, delete is a better option.

EDIT: Ok, it looks like your actual question is "How can I remove a value from an array?", since that's what you're doing - the fact that your array is within an object, or contains objects rather than other values, is irrelevant. To do this, use the splice() method:

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

(Rewritten for corrected question.)

You can write:

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

to delete list[value][index] and thereby shorten the array by one. (The above "replaces" 1 element, starting at position index , with no elements; see splice in MDN for general documentation on the method.)

Here is an example using splice:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM