如前所述,Array
s 和Object
s 是不同的。我并不真正遵循您从一种结构转换为另一种结构的推理,您可能应该考虑以不同的方式工作,这完全可以从您的问题和评论描述中获得。但是,如果你真的必须转换,那么你将需要执行某种映射,往返,以确保正确排序。你可以做这样的事情。
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);
在jsfiddle 上
使用 ECMA5Array.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);
在jsfiddle 上