-2

Ho can I convert this :

var arr = [{"1":["34"]},{"2":["32","31","30"]},{"3":["29","28","27","26"]}]

to this:

{"1":["34"],"2":["32","31","30"],"3":["29","28","27","26"]}

Is there a function in jQuery to do it ?

oussama kamal
  • 1,027
  • 2
  • 20
  • 44

3 Answers3

0

You could use Object.assign with spread syntax ....

var array = [{ 1: ["34"] }, { 2: ["32", "31", "30"] }, { 3: ["29", "28", "27", "26"] }],
    object = Object.assign({}, ...array);
    
console.log(object)
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • why there is ...array (3 dots) is this the synthax ? – oussama kamal Jan 05 '18 at 21:28
  • it it the spread syntax, which takes an array and use it as parameters for the function call. – Nina Scholz Jan 05 '18 at 21:29
  • you _can_ avoid the spread: `Object.assign.apply({}, [{ 1: ["34"] }, { 2: ["32", "31", "30"] }, { 3: ["29", "28", "27", "26"] }]);` of course, not too many places will have `Object.assign()` but not spread support, but a partial poly-fill of assign() can support the above in ES5. – dandavis Jan 05 '18 at 21:35
  • jshint does not accept the spread syntax I get message: 'Unexpected token: punc (.)', – oussama kamal Jan 05 '18 at 21:35
0

Or you could do it in "old style":

var src = [{"1":["34"]},{"2":["32","31","30"]},
      {"3":["29","28","27","26"]}], trg = {};

src.forEach((e)=>{for(var p in e) trg[p]=e[p];});
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
-1
 arr.reduce((obj, arrayElem) => Object.assign(obj, arrayElem), {})

Just reduce the array by assigning all Objects together. Or:

 Object.assign({}, ...arr)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151