As already stated, Array
s and Object
s are different. I don't really follow your reasoning for converting from one structure to the other, and you should probably consider working in a different way, which is totally possible from your question and comment descriptions. But, if you really must convert then you will need to perform some kind of mapping, to and from, to be sure that things are ordered correctly. You could do something like this.
Javascript
function toMapped (array) {
var mapping = {
"Nome": 0,
"Departamento": 1,
"Cargo": 2
},
mapped = [],
length = array.length,
i = 0,
element,
j;
while (i < length ) {
element = [];
for (j in mapping) {
if (mapping.hasOwnProperty(j) && array[i].hasOwnProperty(j)) {
element[mapping[j]] = array[i][j];
}
}
mapped.push(element);
i += 1;
}
return mapped;
}
function fromMapped (array) {
var mapping = {
0: "Nome",
1: "Departamento",
2: "Cargo"
},
mapped = [],
length = array.length,
i = 0,
object,
j;
while (i < length ) {
object = {};
for (j in mapping) {
if (mapping.hasOwnProperty(j) && array[i].hasOwnProperty(j)) {
object[mapping[j]] = array[i][j];
}
}
mapped.push(object);
i += 1;
}
return mapped;
}
var test = [{
"Nome": "1",
"Departamento": "1",
"Cargo": "1"
}, {
"Nome": "5",
"Departamento": "5",
"Cargo": "5"
}, {
"Nome": "2",
"Departamento": "2",
"Cargo": "2"
}, {
"Nome": "3",
"Departamento": "33",
"Cargo": "33"
}, {
"Nome": "4",
"Departamento": "4",
"Cargo": "4"
}];
var mapped = toMapped(test);
var unmapped = fromMapped(mapped);
console.log(test);
console.log(mapped);
console.log(unmapped);
On jsfiddle
Using ECMA5 Array.prototype.map
Javascript
function toMapped(array) {
var mapping = {
"Nome": 0,
"Departamento": 1,
"Cargo": 2
};
return array.map(function (object) {
var element = [],
i;
for (i in mapping) {
if (mapping.hasOwnProperty(i) && object.hasOwnProperty(i)) {
element[mapping[i]] = object[i];
}
}
return element;
});
}
function fromMapped(array) {
var mapping = {
0: "Nome",
1: "Departamento",
2: "Cargo"
};
return array.map(function (element) {
var object = {},
i;
for (i in mapping) {
if (mapping.hasOwnProperty(i) && element.hasOwnProperty(i)) {
object[mapping[i]] = element[i];
}
}
return object;
});
}
var test = [{
"Nome": "1",
"Departamento": "1",
"Cargo": "1"
}, {
"Nome": "5",
"Departamento": "5",
"Cargo": "5"
}, {
"Nome": "2",
"Departamento": "2",
"Cargo": "2"
}, {
"Nome": "3",
"Departamento": "33",
"Cargo": "33"
}, {
"Nome": "4",
"Departamento": "4",
"Cargo": "4"
}];
var mapped = toMapped(test);
var unmapped = fromMapped(mapped);
console.log(test);
console.log(mapped);
console.log(unmapped);
On jsfiddle