0

I have a Json var, and I want to add new array into it.

I would like to get:

myJson = {
   "field1":"value1",
   "field2":"value2",
   "newArray":[
       {"array1": "valueArray1"},
       {"array2":"valueArray2"}
   ]
}

var newArray = [{"array1": "valueArray1"},{"array2":"valueArray2"}];

var myJson = {
   "field1":"value1",
   "field2":"value2"
}

var newArray = [{"array1": "valueArray1"},{"array2":"valueArray2"}];


myJson.push(newArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

it return an error:

uncaught TypeError: myJson.push is not a function
at <anonymous>:1:8

why is it incorrect?

3
  • 1
    myJson is not a jsonArray, its an object Commented Apr 27, 2017 at 8:26
  • please use different names for non JSON objects. your variable with the name myJson is not an array. Commented Apr 27, 2017 at 8:27
  • @AlexandruSeverin it's an object - nothing to do with JSON. JSON is just a method of encoding a string. Commented Apr 27, 2017 at 8:27

1 Answer 1

4

Let's set properties instead, because your myJson is object not Array

var myJson = {
   "field1":"value1",
   "field2":"value2"
}

var newArray = [{"array1": "valueArray1"},{"array2":"valueArray2"}];


myJson.newArray = newArray;
console.log(myJson);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.