0

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'
        }
    ]
};

3 Answers 3

1

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 (e.g. 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
Sign up to request clarification or add additional context in comments.

1 Comment

I fixed my main post, I outlined the wrong part I want to delete.
0

(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.)

Comments

0

Here is an example using splice:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.