I am trying to convert this multidimensional array to object, yet when I run it I get the second part of the array saved into the object and the first part is missing.
How do I get the whole array saved in the object?
var array = [
[
['name', 'John Smith'],
['age', 34],
['occupation', 'nurse']
],
[
['name', 'Nico Klein'],
['age', 24],
['occupation', 'engineer']
]
];
function toObject(arr) {
var obj = {};
for (var j = 0; j < arr.length; j++) {
for (var i = 0; i < arr[j].length; i++) {
obj[arr[j][i][0]] = arr[j][i][1];
}
}
return obj;
}
var result = toObject(array);
console.log(result);
And is there a better method of writing this?
2 Answers 2
You have done almost well, but the parent should be array of objects, which makes sense.
var array = [
[
['name', 'John Smith'],
['age', 34],
['occupation', 'nurse']
],
[
['name', 'Nico Klein'],
['age', 24],
['occupation', 'engineer']
]
];
function toObject(arr) {
var obj = [];
for (var j = 0; j < arr.length; j++) {
var cur = {};
for (var i = 0; i < arr[j].length; i++) {
cur[arr[j][i][0]] = arr[j][i][1];
}
obj.push(cur);
}
return obj;
}
var result = toObject(array);
console.log(result);
The output will be in the order of:
[
{
"name": "John Smith",
"age": 34,
"occupation": "nurse"
},
{
"name": "Nico Klein",
"age": 24,
"occupation": "engineer"
}
]
And it has all the records from the original array. If you still want to convert the resultant array into an object, look at Convert Array to Object.
var array = [
[
['name', 'John Smith'],
['age', 34],
['occupation', 'nurse']
],
[
['name', 'Nico Klein'],
['age', 24],
['occupation', 'engineer']
]
];
function toObject(arr) {
var obj = [];
for (var j = 0; j < arr.length; j++) {
var cur = {};
for (var i = 0; i < arr[j].length; i++) {
cur[arr[j][i][0]] = arr[j][i][1];
}
obj.push(cur);
}
return obj;
}
var result = toObject(array);
var resObj = result.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
console.log(resObj);
The final Object output will give you:
{
"0": {
"name": "John Smith",
"age": 34,
"occupation": "nurse"
},
"1": {
"name": "Nico Klein",
"age": 24,
"occupation": "engineer"
}
}
Comments
First of all you should try to convert that array to "array of objects", this makes sense because you have two elements in the array. So you should try to get array of objects.
Secondly this program is correct but there is a mistake. Look at your code you
have created a var obj = {}; which is an object and you are assigning the array values it should be array of object so change the function as follows
function toObject(arr) {
var arrOfObj = [];
for (var j = 0; j < arr.length; j++) {
var curObj = {};
for (var i = 0; i < arr[j].length; i++) {
curObj[arr[j][i][0]] = arr[j][i][1];
}
arrOfObj.push(cur);
}
return arrOfObj;
}
Comments
Explore related questions
See similar questions with these tags.
arr[j][i][0]is the same value each iteration, so it just overwrites the existing value. For example fornameit's doing:obj.name = 'John Smith'thenobj.name = 'Nico Klein'.