I am trying to merge 4 arrays into 1 single array using javascript and throws error.
var dif1 = {name: 'sree', age:'33'};
var dif2 = {name: 'kavitha', age:'34'};
var dif3 = {name: 'darshan', gender:'Male'};
var dif4 = {name: 'suchi', gender:'Female'};
I want results like below
{
{name: 'sree', age:'33'},
{name: 'kavitha', age:'34'},
{name: 'darshan', gender:'Male'},
{name: 'suchi', gender:'Female'}
}
I have tried with concat method and it’s throwing an error saying .concat is not a function.
5
Answers
What you are showing here are not arrays but these are objects. Object is a structure that has a key and a value. You might be confused because in some languages, objects are called associative arrays.
You can merge the four objects into one array using the
concat()
method or the spread operator.Both will return the same value
Those are 4 objects and you are trying to put objects in an object without a key value pair, and if you want to make a array of them then use below code. Try to run the snippet to see the result.
If the objects: dif1, dif2, dif3, dif4, are hardcoded you could create an array of objects to begin with:
and if you want to add new objects to the array later:
Here are all the methods that are available besides
push
on an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methodsIn terms of merging multiple objects into a single object, it can be done using two methods.
1st method:
2nd method:
is not an object, javascript objects are key:value structred.
if you want to merge into one object, you should add keys for each array.
if you want to merge into one array, you should make the {} into [] .