Home > Mobile >  Combining two arrays into an object
Combining two arrays into an object

Time:11-26

I have two arrays one with label date i.e [Date, Date, Date ...] and

the other with the actual date data i.e [2021-11-26, 2021-11-25, ...].

I want to combine these two arrays such that I get array of objects such as [ { Date: 2021-11-26}, {Date:2021-11-25}, {..}, ...].

I have tried these two methods

obj = {};

for (var i = 0, l = date_label.length; i < l; i  = 1) {
    obj[date_label[i]] = data_date[i]
}
console.log(obj);

and

_.zipObject(date_label, data_date);

However it only ends up giving me the last date of my data set, in an object data structure ie { Date: 1999-11-24}

CodePudding user response:

The keys inside an object / associative array are unique. Your obj is such a thing. If you turn it into a regular array and push new objects into it, it will work.

const obj = [];
for (let i = 0, l = date_label.length; i < l; i  ) {
    obj.push({[date_label[i]]: data_date[i]})
}
console.log(obj);

You should probably assert that both your arrays have the same length.

CodePudding user response:

The issues you are facing is that your date_label are the same and the loop are replacing the dates on the same label, again and again, you just need to change the label name and give unique to each one or you change them into the loop as well like this (obj[date_label[i] str(i)] = data_date[i]).

date_label = ['date1', 'date2', 'date3', .....]

obj = {};

for (var i = 0, l = date_label.length; i < l; i  = 1) {
    obj[date_label[i]] = data_date[i]
}
console.log(obj);

CodePudding user response:

obj is of type array not object. data_date needs to be in string format.

for(var i= 0; i<data_date.length-1;i  ) {
obj.push({"Date":date_date[i]}) }

CodePudding user response:

with array reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

var myFinalArray = data_date.reduce(
(previousValue, currentValue, currentIndex, array) => ({ 
    currentValue: date_label[currentIndex]
}), {});
  • Related