How to Add an Object to an Array
How Can I Add an Object to an Array (In Javascript or Jquery)? for Example, What Is the Problem with This Code? Function() { Var a = New Array(); Var B = New...
How can I add an object to an array (in javascript or jquery)? For example, what is the problem with this code?
function() {
var a = new array();
var b = new object();
a[0] = b;
}
I would like to use this code to save many objects in the array of function1 and call function2 to use the object in the array.
- How can I save an object in an array?
- How can I put an object in an array and save it to a variable?
15 Answers
Put anything into an array using Array.push().
var a=[], b={};
a.push(b);
// a[0] === b;
Extra information on Arrays
Add more than one item at a time
var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']
Add items to the beginning of an array
var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']
Add the contents of one array to another
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f'] (remains unchanged)
Create a new array from the contents of two arrays
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c'] (remains unchanged)
// y = ['d', 'e', 'f'] (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']
var years = [];
for (i= 2015;i<=2030;i=i+1){
years.push({operator : i})
}
here array years is having values like
years[0]={operator:2015}
years[1]={operator:2016}
it continues like this.
First of all, there is no object or array. There are Object and Array. Secondly, you can do that:
a = new Array();
b = new Object();
a[0] = b;
Now a will be an array with b as its only element.
Using ES6 notation, you can do something like this:
For appending you can use the spread operator like this:
var arr1 = [1,2,3]
var obj = 4
var newData = [...arr1, obj] // [1,2,3,4]
console.log(newData);
- JavaScript is case-sensitive. Calling
new array()andnew object()will throw aReferenceErrorsince they don't exist. - It's better to avoid
new Array()due to its error-prone behavior.
Instead, assign the new array with= [val1, val2, val_n]. For objects, use= {}. - There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use
concatinstead ofpush.concatreturns a new array, leaving the original array untouched.pushmutates the calling array which should be avoided, especially if the array is globally defined. - It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).
Applying those points and to answer your two questions, you could define a function like this:
function appendObjTo(thatArray, newObj) {
const frozenObj = Object.freeze(newObj);
return Object.freeze(thatArray.concat(frozenObj));
}
Usage:
// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.
/* array literal */
var aData = [];
/* object constructur */
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = function() {
// return (this.firstname + " " + this.lastname);
return (`${this.firstname} ${this.lastname}`); // es6 template string
};
}
/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]
aData.push(new Person("John", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));
aData[aData.length] = new Person("stack", "overflow"); // aData[4]
/* loop array */
for (var i in aData) {
alert(aData[i].fullname());
}
/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);
With push you can even add multiple objects to an array
let myArray = [];
myArray.push(
{name:"James", dataType:TYPES.VarChar, Value: body.Name},
{name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
{name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
);
Expanding Gabi Purcaru's answer to include an answer to number 2.
a = new Array();
b = new Object();
a[0] = b;
var c = a[0]; // c is now the object we inserted into a...
obejct is clearly a typo. But both object and array need capital letters.
You can use short hands for new Array and new Object these are [] and {}
You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.
function saveToArray() {
var o = {};
o.foo = 42;
var arr = [];
arr.push(o);
return arr;
}
function other() {
var arr = saveToArray();
alert(arr[0]);
}
other();
On alternativ answer is this.
if you have and array like this: var contacts = [bob, mary];
and you want to put another array in this array, you can do that in this way:
Declare the function constructor
function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}
make the object from the function:
var add1 = new add("Alba","Fas","","[098] 654365364");
and add the object in to the array:
contacts[contacts.length] = add1;
You can use with Spread Operator (...) like this:
let arr = [{num: 1, char: "a"}, {num: 2, char: "b"}];
arr = [...arr,{num: 3, char: "c"}];
//...arr --> spread operator
console.log(arr);
a=[];
a.push(['b','c','d','e','f']);
The way I made object creator with auto list:
var list = [];
function saveToArray(x) {
list.push(x);
};
function newObject () {
saveToArray(this);
};
Performance
Today 2020.12.04 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v83 for chosen solutions.
Must Read
Results
For all browsers
- in-place solution based on
length(B) is fastest for small arrays, and in Firefox for big too and for Chrome and Safari is fast - in-place solution based on
push(A) is fastest for big arrays on Chrome and Safari, and fast for Firefox and small arrays - in-place solution C is slow for big arrays and medium fast for small
- non-in-place solutions D and E are slow for big arrays
- non-in-place solutions E,F and D(on Firefox) are slow for small arrays