skip to Main Content

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


  1. Use Array.map() to transform you values into an array and Array::filter() to filter out values before the mapping.
    Also you don’t need Object.entries() because you don’t use the keys, use Object.values instead.

    Object.values(buyProductData)
        .filter(value => typeof value === 'object')
        .map(value => {
            const obj = JSON.parse(value.getAttribute('data-tracking-payload'));
            obj.DUS = obj.sku;
            delete obj.sku;
            return obj;
        });
    

    You could also Array::reduce():

    Object.values(buyProductData).reduce((arr, value) => {
        if(typeof value === 'object'){
            const obj = JSON.parse(value.getAttribute('data-tracking-payload'));
            obj.DUS = obj.sku;
            delete obj.sku;
            arr.push(obj);
        }
        return arr;
    }, []);
    
    Login or Signup to reply.
  2. Before you iterate over objects, create an array and with each iteration add the object to that array with Array#push:

    const arr = [];
    Object.entries(buyProductData).forEach(entry => {
        const [key, value] = entry;
        if(typeof value === 'object') {
            const {sku,...restProperties} = JSON.parse(value.getAttribute('data-tracking-payload'));
            // console.log(data);
            arr.push({DUS:sku,...restProperties});
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search