0

I have an associative array stored in another associative array. I know how to splice a specific value in just a regular array as such:

arr.splice(arr.indexOf('specific'), 1);

I was wondering how one could splice an array such as this:

arr['hello']['world']

EDIT Would this shorten hello['world']['continent']

var hello = {};
            hello['world'] = {};
            hello['world']['continent'] = "country";
            delete hello['world']['continent'];
            alert(hello['world']['continent'])
re1man
  • 2,337
  • 11
  • 38
  • 54

3 Answers3

2

You should be able to just just use the delete keyword.

delete arr["hello"]["world"]

How do I remove objects from a javascript associative array?

Edit, based on other comments:

For the sake of readability, you can also do:

delete arr.hello.world

Since we are really just talking about objects, and not traditional arrays, there is no array length. You can however delete a key from an object.

Community
  • 1
  • 1
GoldenNewby
  • 4,382
  • 8
  • 33
  • 44
  • would this shorten the array though? – re1man Mar 07 '12 at 19:46
  • It would remove the world object all together. So, it would shorten arr["hello"] – GoldenNewby Mar 07 '12 at 19:48
  • wouldn't it just make it undefined...im pretty sure – re1man Mar 07 '12 at 19:49
  • I agree with Praneet Sharma. delete sets an item undefined while splice actually "shortens". – tamarintech Mar 07 '12 at 19:50
  • @esnyder: JavaScript doesn't have "associative" arrays. If the key is `"hello"`, that means `arr` is an object, not an array, so it doesn't have a length (so "shorten" doesn't make sense here). – gen_Eric Mar 07 '12 at 19:52
  • `delete` used on an array will leave a space with `undefined`, but used on an object, it will remove the property. – gen_Eric Mar 07 '12 at 19:53
  • 1
    I was thinking of the length more in the context of listing the keys of the object. In that case I believe it would shorten the list of keys. – GoldenNewby Mar 07 '12 at 19:58
  • 1
    @Rocket The reason I put "shortens" in those quotes is exactly what you're suggesting... "shortens" doesn't make sense (exactly as you said). That's what I was trying to communicate. :) – tamarintech Mar 07 '12 at 20:06
1

JavaScript does not have associative arrays.

Use objects:

var x = {
  a : 1,
  b : 2,
  c : {
     a : []
  }
}

delete x.c.a;
max
  • 96,212
  • 14
  • 104
  • 165
0

An "associative array" in javascript isn't actually an array, it's just an object that has properties set on it. Foo["Bar"] is the same thing as Foo.Bar. So you can't really talk about slicing or length here.

bhamlin
  • 5,177
  • 1
  • 22
  • 17