0

I have an array from json like this:

{"1001":"Account1","1002":"Account2","1003":"Account3"}

and i need convert it to key value format:

[{id:"1001",name:"Account1"},
{id:"1002",name:"Account2"},
{id:"1003",name:"Account3"}]

To do this i wrote this function:

function arrayToMultiArray(list) {
    var matrix = [], i;
    i = -1;
    for (var key in list) {
        i++;
        matrix[i] = [];
        matrix[i].push({"id":key, "name":list[key]});
    }
    return matrix;
}

but the generated array has brackets for each array

[[{id:"1001",name:"Account1"}],
[{id:"1002",name:"Account2"}],
[{id:"1003",name:"Account3"}]]

How can i remove brackets of internal arrays?

3 Answers 3

3

You added array in array.

Just change

i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});

to

matrix.push({"id":key, "name":list[key]});
Sign up to request clarification or add additional context in comments.

Comments

1

you are creating a multidimensional array.

remove this

 i++;
 matrix[i] = [];

and do this directly

matrix.push({"id":key, "name":list[key]});

Comments

1

You could do the same with Object.keys and Array.prototype.map

var obj = {"1001":"Account1","1002":"Account2","1003":"Account3"};
var arr = Object.keys(obj).map(function(key) {
  return { id : key, name : obj[key] }
});

console.log(arr);

Comments

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.