1

I have a variable defined like this :

Var France ={

'Nice': {

    inputs: _.extend({
        attrs: {
            text : inp({
                text: { group: 'data', index: 1 },
                'font-size': { group: 'text', index: 2 },
                'font-family': { group: 'text', index: 3 },
                'font-weight': { group: 'text', index: 4 },

            }),
            image: inp({
                'xlink:href': { group: 'presentation', index: 1 }
            })
        },

    }),
    groups: cities

}};

var Paris =  {

    inputs: _.extend({
        attrs: {
            text : inp({
                text: { group: 'data', index: 1 },
                'font-size': { group: 'text', index: 2 },
                'font-family': { group: 'text', index: 3 },
                'font-weight': { group: 'text', index: 4 },

            }),
            image: inp({
                'xlink:href': { group: 'presentation', index: 1 }
            })
        },

    }),
    groups: cities

};

How can i push another city in France dynamically, like $(France).push(Paris) itried this but it dosent work, how can i make this work ?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
azelix
  • 1,257
  • 4
  • 26
  • 50
  • Also a duplicate of [How can I add a key/value pair to a JavaScript object literal?](http://stackoverflow.com/q/1168807/218196) – Felix Kling Jun 18 '15 at 08:47

2 Answers2

2

as simple as:

France['Paris'] = { ... }

or

France.Paris = { ... }

You can use the push operation only on arrays (or other types which support this, but it's more advanced). You cannot push to objects, because they are not ordered.

An array is ordered, therefore you can use:

  • push to add an element to the end
  • pop to remove the element from the end and return it
  • unshift to add an element to the beginning
  • shift to remove the element from the beginning and return it.

The usage:

var x = [];
x.push(1);
//x is now [1];
x.unshift(2);
//x is now [2,1];
Liglo App
  • 3,719
  • 4
  • 30
  • 54
  • Thank you for your explanation it's more clear for me now i knew i was doing something wrong. I ll accept your answer when in a few minutes when the site let me do it – azelix Jun 18 '15 at 08:50
  • Thank you a lot, I'm glad it helped. – Liglo App Jun 18 '15 at 08:51
1

Object is not an Array. To create a new field you have to do something like

Paris["newkey"] = "aValue"; //Any value like {}, "", [], 0
steo
  • 4,586
  • 2
  • 33
  • 64