Remove value from associative array
Possible Duplicate:
Remove specific element from a javascript array?
I am having an array, from which I want to remove a value.
Consider this as an array
[ 'utils': [ 'util1', 'util2' ] ]
Now I just want to remove util2
. How can I do that, I tried using delete
but it didn't work.
Can anyone help me?
Use the splice
method:
var object = { 'utils': [ 'util1', 'util2' ] }
object.utils.splice(1, 1);
If you don't know the actual position of the array element, you'd need to iterate over the array and splice the element from there. Try the following method:
for (var i = object.utils.length; i--;) {
var index = object.utils.indexOf('util2');
if (index === -1) break;
if (i === index) {
object.utils.splice(i, 1); break;
}
}
Update: techfoobar's answer seems to be more idiomatic than mine. Consider using his instead.
您可以在Array.splice()
组合中使用Array.indexOf()
来获得所需的行为,而不必遍历数组:
var toDelete = object.utils.indexOf('util1');
if(toDelete != -1) {
object.utils.splice(toDelete, 1);
}
I think there is no such thing called associative array in Javascript. It is actually an object.
[ 'utils': [ 'util1', 'util2' ] ]
For this line, I don't think it would compile. You should write this instead.
var obj = { 'utils': [ 'util1', 'util2' ] }
So to remove the element "util2" in the array (the inside array), there are 2 ways.
use pop()
obj["utils"].pop(); // obj["utils"] is used to access the "property" of the object, not an element in associative array
reduce the length
obj["utils"].length --;
上一篇: 从Javascript对象中删除单个对象
下一篇: 从关联数组中删除值