Combine Array(s) into single object in JavaScript

  • A+
Category:Languages

Currently I have 3 arrays:

var idArray = [13, 24, 35];     var dateArray = [20181920, 20181120, 20172505]; var contentArray = ["content1", "content2", "content3"]; 

I would like to merge all the array into one object instead and I tried using for loop but got an error instead:

var finalObj = {};  for (var y = 0; y < dateArray.length; y++) {      finalObj[y].id = idArray[y];     finalObj[y].date =  dateArrayArrange[y];     finalObj[y].content =  contentArray[y];  } 

The end result I want to achieve:

finalObj = [{id:13, date:20181920, content:"content1"},           {id:24, date:20181120, content:"content2"},           {id:35, date:20172505, content:"content3"}]; 

 


Your finalObj is an array of objects, so you must initialise it as an array, like this :

var finalObj = []; var idArray = [13, 24, 35]; var dateArray = [20181920, 20181120, 20172505]; var contentArray = ["content1", "content2", "content3"];  for (var y = 0; y < dateArray.length; y++) {   finalObj.push(     { id: idArray[y], date: dateArray[y], content : contentArray[y] }   ) } 

for the "pushing to final array" part, your code inside the loop may work if you add an extra finalObj[y] = {} to initialise it and so you have :

for (var y = 0; y < dateArray.length; y++) {   finalObj[y] = {}     finalObj[y].id = idArray[y];   finalObj[y].date = dateArray[y];   finalObj[y].content = contentArray[y]; } 

an it works but

  finalObj.push(     { id: idArray[y], date: dateArray[y], content : contentArray[y] }   ) 

is shorter and still readable i think :)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: