Spread returned objects from map into one object

169 views Asked by At

I'm trying to get the results back from my loop to be spread into a variable

const updateds = {
    ...
        (Array.from(document.querySelectorAll('.updated')).map(item => {
            return {[item.dataset.slug]: item.dataset.position};
        }))
};

and the results should be spread to form like so

{"chahan": "1", "jacques-lacoste": "2", "testcover": "3", "kreo": "4"}

but instead i get

{"chahan":"1"},{"jacques-lacoste":"2"},{"testcover":"3"},{"kreo":"4"}

Any idea how to achieve so ?

2

There are 2 answers

0
Nitsew On BEST ANSWER

Using the map higher-order method is always going to return an array. If you want to combine the objects of an array into a single object, the reduce higher-order method is what you want to use.

const updateds = Array.from(document.querySelectorAll('.updated')).reduce((accumulator, item) => {
  return {
    ...accumulator,
    [item.dataset.slug]: item.dataset.position
  };
}, {})
0
سعيد On

you can use Array.reduce

const updateds =Array.from(document.querySelectorAll('.updated')).map(item => {
            return {[item.dataset.slug]: item.dataset.position};
        })
;

const reducedResult=updateds.reduce((obj, Currentitem) =>Object.assign(obj,Currentitem), {})