JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
Answer from Paul S. on Stack Overflow
Top answer
1 of 6
303

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
2 of 6
29
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

If you want to add at last position then use this:

var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

If you want to add at first position then use the following code:

var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"

Anyone who wants to add at a certain position of an array try this:

parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"

Above code block adds an element after the second element.

🌐
HowToDoInJava
howtodoinjava.com › home › typescript › typescript – how to add items to array
TypeScript - How to Add Items to Array
July 26, 2023 - Learn to add or append or push new items into an array in TypeScript. Also, learn to append or merge an array into a specified array.
🌐
TutorialsPoint
tutorialspoint.com › home › typescript › typescript array push method
TypeScript Array Push Method
December 18, 2016 - Learn how to use the Array Push method in TypeScript to add elements to an array efficiently. Discover examples and best practices.
🌐
TutorialsPoint
tutorialspoint.com › home › typescript › typescript array concat
TypeScript Array Concat
December 18, 2016 - TypeScript - null vs. undefined ... Returns a new array.
🌐
Quora
quora.com › I-want-to-add-a-new-JSON-object-to-the-already-existing-JSON-Array-What-are-some-suggestions
I want to add a new JSON object to the already existing JSON Array. What are some suggestions? - Quora
Answer (1 of 5): Simply use push method of Arrays. [code]var data = [ { name: "Pawan" }, { name: "Goku" }, { name: "Naruto" } ]; var obj = { name: "Light" }; data.push(obj); console.log(data); /* 0:{name:"Pawan"} 1:{name: "Goku"} 2:{name: "Naruto"} ...
Top answer
1 of 1
186

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];

array1.pushArrayMembers(array2, array3);

document.body.textContent = JSON.stringify(array1, null, 4);

Find elsewhere
🌐
Reddit
reddit.com › r/learnjavascript › can you only add an array to another array?
r/learnjavascript on Reddit: Can you only add an array to another array?
October 4, 2022 -

Hi there!

I'm new to JavaScript and was learning about arrays today and saw that the instructor only added an array to another array. Is it possible to add something that is not an array into an array? Iyes, how can I do that?

Thanks in advance!

Top answer
1 of 16
5428

Use the Array.prototype.push method to append values to the end of an array:

Copy// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand


You can use the push() function to append more than one value to an array in a single call:

Copy// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Note that the push() method returns the updated length of the array.


Update

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

Copyvar arr = [
  "apple",
  "banana",
  "cherry"
];

// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Update

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

Copyvar arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

It also supports appending multiple values at once just like push.


Update

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended or prepended, compliant with the spirit of functional programming.

Copyconst arr1 = [
  "Hi",
  "Hello",
  "Bonjour",
];
const arr2 = [
  "Ciao",
  "Hej",
  "Merhaba",
];

const newArr1 = [
  ...arr1,
  "Salut",
];
const newArr2 = [
  "Salut",
  ...arr2,
];
const newArr3 = [
  ...arr1,
  ...arr2,
];

console.log(newArr1, newArr2, newArr3);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
1122

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():

Copyvar ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar1);
alert(ar2);
alert(ar3);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

The concat does not affect ar1 and ar2 unless reassigned, for example:

Copyvar ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

ar1 = ar1.concat(ar2);
alert(ar1);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

There is a lot of great information on JavaScript Reference.

🌐
Quora
quora.com › How-do-you-add-elements-to-a-JSON-Array
How to add elements to a JSON Array - Quora
Answer (1 of 3): Here’s how you add elements to a JSON array—let’s break it down like you’re sitting around a table with a laptop, trying to figure this out. So, first off, JSON arrays are those square-bracket lists of stuff, right? Like `["apple", "banana"]`. To add something, you ...
🌐
EyeHunts
tutorial.eyehunts.com › home › how to add json object to existing json array in javascript | example
How to add JSON object to existing JSON array in JavaScript | Code
November 23, 2022 - Answer: If there is a single object and you want to push the whole object into an array then you do simply push the object. var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}; var data = []; ...
🌐
Reddit
reddit.com › r/learnjavascript › how do i append to an array inside a json file in node?
r/learnjavascript on Reddit: How do I append to an array inside a json file in node?
December 26, 2022 -

I’m working on a chat client and server to learn about API’s and now I need to write the messages submitted by users into the master chat log (a json file with a messages array inside of it). I have been searching for different approaches and they all error out somehow. I’m using node and express for routing if that helps.

tldr; how should one append an object to an array inside a json file using node.

edit: I’ve taken carcigenocate’s advice. I open the file, make the changes in memory, then write to the file and reload it to reflect changes. I am still open to improvements on this design!

🌐
Reddit
reddit.com › r/typescript › help with handling json array of objects (merge two arrays)
r/typescript on Reddit: Help with handling JSON array of objects (merge two arrays)
May 14, 2020 -

I have a json array of Objects and need to pick a corresponding object in that array according to some calculations.

My json have a following structure: {"OD": number, "SCH" {"SCH40": number, "SCH80": number}}

I need to do some math with OD and SCH numbers, compare it with an outside number and find corresponding value for OD key.

I can get a new array (of numbers I compare the outside number with):

this.Pipeareas = this.Pipesizes.map (x => Math.pow((x.OD - 2 * x.SCH[this.selectedSCH])/2000,2) * Math.PI);

How to merge existing and new arrays?

I tried (this add extra existing array and new object to new array (not key:value pair))

this.Pipeareas = {...this.Pipesizes, Area: this.Pipesizes.map (x => Math.pow((x.OD - 2 * x.SCH[this.selectedSCH])/2000,2) * Math.PI) }

and (this adds new key "Area" to each object but the value is full array, not corresponding numbers from new array)

this.Pipesizes.map (x => x.Area = this.Pipesizes.map (x => Math.pow((x.OD - 2 * x.SCH[this.selectedSCH])/2000,2) * Math.PI))

The result should be like:

return this.Pipeareas.find(x => x >= this.OutsideNumber);

🌐
Reddit
reddit.com › r/learnjavascript › three ways to append an item to an array (mutative)
r/learnjavascript on Reddit: Three ways to append an item to an array (Mutative)
September 1, 2022 - I actually think you should use whatever makes sense for your use case. if you have a really large array then use push(or whatever the researched most efficient method is)
🌐
WebDevAssist
webdevassist.com › typescript › typescript-array-push
How to add elements to an Array in TypeScript
This method adds items to the end of an array and returns the length. In this post, we will learn how to use the push method with example. ... Where, e1, e2, etc. are elements to append to the array.
🌐
Medium
dpericich.medium.com › how-to-push-elements-to-a-typescript-array-ea9a899687f8
How to Push Elements to a TypeScript Array | by Daniel Pericich | Medium
June 12, 2022 - TypeScript has a special never type that applies to empty type declarations and errors when pushing items to the array. In this article we examine never and
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › add-an-object-to-an-array-in-typescript
Add an Object to an Array in TypeScript - GeeksforGeeks
August 5, 2025 - Example: In this example we initializes an array of products, appends a new product object to it using concat(), and logs the updated array with the new product included.