I’m looping through and object and getting the data-attributes
. After that I’m parsing it as a JSON.
Object.entries(buyProductData).forEach(entry => {
const [key, value] = entry;
if(typeof value === 'object') {
const data = JSON.parse(value.getAttribute('data-tracking-payload'));
console.log(data);
}
});
console.log(data)
returns two objects:
{pid: '9783834649867', sku: '9783834649867', name: 'Book 1}
{pid: '9683271123215', sku: '7552163721', name: 'Book 2}
My question is now how can I combine the two objects so I can have a single one that looks like this:
ec_Event : [
{
pid: '9783834649867', sku: '9783834649867', name: 'Book 1
}, {
pid: '9683271123215', sku: '7552163721', name: 'Book 2
}
]
I tried let merge = {...data}
, but it doesn’t seem to merge them.
Thanks!
2
Answers
Use
Array.map()
to transform you values into an array andArray::filter()
to filter out values before the mapping.Also you don’t need
Object.entries()
because you don’t use the keys, useObject.values
instead.You could also
Array::reduce()
:Before you iterate over objects, create an array and with each iteration add the object to that array with
Array#push
: