1

I have an array. And i want to convert them into a group of objects.

below is my array

[ null,
[ 5, 6 ],
[ 7, 8 ],
[ 9, 10 ],
[ 13, 14 ] ]

Then i tried them to convert into object by pairs but what i had was this:

{ '0': null,
'1': [ 5, 6 ],
'2': [ 7, 8 ],
'3': [ 9, 10 ],
'4': [ 13, 14 ] }

What i'm trying to achieve is something like below:

    {
        "0": 5,
        "1": 6,
    },
    {
        "0": 7,
        "1": 8,
    },
    {
        "0": 9,
        "1": 10,
    },
    {
        "0": 13,
        "1": 14,
    },

thank you for those who will help

Tramyer
  • 19
  • 4
  • 1
    What you tried? please attach the relevant code to the question – Michael Jun 12 '18 at 11:25
  • https://stackoverflow.com/questions/4215737/convert-array-to-object – Akhil Aravind Jun 12 '18 at 11:32
  • @AkhilAravind bro yeah i saw that post and im having the above result and not the result i wanted. I believe that code is for when you have a single array but it coulde be reused and needs a bit of tweaks in order to achieve my goal – Tramyer Jun 12 '18 at 11:48

2 Answers2

2

You could filter falsy values and map objects where you have assigned the array.

var array = [null, [5, 6], [7, 8], [9, 10], [13, 14]],
    result = array
        .filter(Boolean)
        .map(a => Object.assign({}, a));
        
console.log(result);

Wrapped in a function

function getObjects(array) {
    return array
        .filter(Boolean)
        .map(a => Object.assign({}, a));
}

console.log(getObjects([null, [5, 6], [7, 8], [9, 10], [13, 14]]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • tried your code but when i tried to create a function with it. im having the same result above. – Tramyer Jun 12 '18 at 11:45
0

You should have a condition that skip the null value in the array:

function changeArray(arr){
  var res = [];
  arr.forEach((item)=>{
    let obj = {};
    if(item){
      item.forEach((val, index)=>{
        obj[index] = val;
      });
     res.push(obj);
    }
  });
  return res;
}

var arr1 = [ null,
[ 5, 6 ],
[ 7, 8 ],
[ 9, 10 ],
[ 13, 14 ] ];
console.log(changeArray(arr1));

var arr2 = [ null,
[ 5, 6, 7 ],
[ 7, 8, 9 ]];
console.log(changeArray(arr2));
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62