Uğurcan Uçar
Uğurcan Uçar

Reputation: 127

Add new element to object after it created

Hello I need make a object in JavaScript. It will show a array-object field named "Cities" then inside of Cities it will give city name, id, key then District array object then it will have town data for that district and city.

How can I add new city after I created an object?

To be clear:

{
  "Cities": [
    {
      "Id": "1",
      "Name": "İstanbul",
      "Key": "asdfas",
      "District": [
        {
          "ID": "aa",
          "Name": "bb",
          "Key": "12",
          "Towns": [
            {
              "Id”:”aa”,
              “Name:”X Town”
            },
            {
              “Id:”bb”,
              “Name:”B Town”
            }
          ]
        }
      ]
    }
  ]
}

It will be like that.

How can I add a new City to it after I created?

İf I do like:

obj.Cities={ 
"ID":"New City",
"Name":"X City",
"Key":"2121",
"District":[
{
.....
}]
}

Like that it's deleting first data and replacing it. I want the 2nd city. How can I add new city after I created?

Upvotes: 0

Views: 73

Answers (1)

Majid M.
Majid M.

Reputation: 4954

You assigned your array :

obj.Cities={ 
"ID":"New City",
"Name":"X City",
"Key":"2121",
"District":[
{
.....
}]
}

which is incorrect and in this situation Cities is an object not an array. You should assigned it with [ ]:

obj.Cities=[{ 
"ID":"New City",
"Name":"X City",
"Key":"2121",
"District":[
{
.....
}]
}]

And for adding new items to array, you can try push method of array:

obj.Cities.push({"ID":"id",
"Name":"cityName",
"Key":"cityKey"});

Upvotes: 3

Related Questions