-3

I have the following object

var foo = {
    "1" : {
        "test1" : "this is a test",
        "test2" : "this is a test2"
    }
}

How would you be able to insert another numerical named element?

    "2" : {
        "test3" : "this is a test3",
        "test4" : "this is a test4"
    }
Gerard Cruz
  • 641
  • 14
  • 34
  • What have you tried already? Note that this answer relies on you knowing the JS object access methods. There are two. – Andy Sep 26 '14 at 14:41
  • I tried foo.1 = {}; and foo."1" = {}; but certainly it doesn't work. How to make the numerical number as a property name? – Gerard Cruz Sep 26 '14 at 14:49
  • @FelixKling, that isn't a duplicate. – Andy Sep 26 '14 at 15:03
  • 1
    Have you ever wondered why you have to use `arr[0]` to access the elements of an array, instead of `arr.0`? You can only use dot notation if the property name is a valid identifier name, i.e. could be used as a variable name (plus reserved words). – Felix Kling Sep 26 '14 at 15:12
  • Fair enough, but if you expect someone who is only just learning JS to understand that I think you're mistaken. Feel free to edit my answer with that information if you think it will help tho. – Andy Sep 26 '14 at 15:18
  • @FelixKling huge thanks. I really have to take note of that. I'm still trying to learn objects and arrays in js - their differences, similarities and how can they work together. – Gerard Cruz Sep 26 '14 at 15:28
  • 2
    Arrays are built on top of objects (so arrays are objects too). They treat numeric properties in a special way, they are the "elements" of the array, and they have additional methods. But because they are objects, you can either use dot notation (`arr.length`) or bracket notation (`arr[0]`) to access their properties. And because numbers can't be variables names (`var 0 = 'foo';` is an error), always have to use bracket notation to access numeric properties (whether you are working with an array or an object). [MDN - Working with Objects](http://mzl.la/QkOHkL) might be helpful. – Felix Kling Sep 26 '14 at 15:33

1 Answers1

2

You can access the object using either dot or square-bracket notation. In this case you need to use square-bracket notation:

foo['2'] = {
  test3: "this is a test3",
  test4: "this is a test4"
}
Andy
  • 61,948
  • 13
  • 68
  • 95