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

3
  • 1
    What you tried? please attach the relevant code to the question Commented Jun 12, 2018 at 11:25
  • stackoverflow.com/questions/4215737/convert-array-to-object Commented Jun 12, 2018 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 Commented Jun 12, 2018 at 11:48

2 Answers 2

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]]));

Sign up to request clarification or add additional context in comments.

1 Comment

tried your code but when i tried to create a function with it. im having the same result above.
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));

4 Comments

How do i turn this into a function? im kinda new to js
@Tramyer see the updated answer. If you are new then use simple loop like above instead of complex filter and map operations. So that you can learn the code style and logic.
thanks mate i've been trying to convert yours into a function but damn im having the same result. Good to see some people here it really helps the new ones.
@Tramyer glad to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.