javascriptarraysobject

Combining two arrays into an object


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}


Solution

  • 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.