Reputation: 13517
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'
}
]
};
Upvotes: 0
Views: 1258
Reputation: 55678
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
Upvotes: 1
Reputation: 1560
Here is an example using splice:
http://jsfiddle.net/hellslam/SeW3d/
Upvotes: 0
Reputation: 183504
(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.)
Upvotes: 0