我计划通过用索引规范分隔那些类型的数组来准备此数组
默认数据格式
[{
"Emp_code": "EM-00001",
"Emp_title": "11",
"Emp_firstName": "22",
"Emp_lastName": "33",
"Emp_dateOfBirth": "20-10-1985",
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}]
想要的格式
[{
"emp": {
"code": "EM-00001",
"title": "11",
"firstName": "22",
"lastName": "33",
"dateOfBirth": "20-10-1985",
},
"con": {
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}
}]
答案 0 :(得分:2)
您可以将属性名称简化为[{emp:{}},{con:{}}]的起始累加器,并且每次迭代都可以将属性添加到累加器中的相应项。
const data = [{
"Emp_code": "EM-00001",
"Emp_title": "11",
"Emp_firstName": "22",
"Emp_lastName": "33",
"Emp_dateOfBirth": "20-10-1985",
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}];
const format = obj =>
Object.getOwnPropertyNames(obj[0]).reduce(
(acc, prop) => {
if (prop.startsWith('Emp_')) {
acc[0].emp[prop.replace('Emp_', '')] = obj[0][prop];
} else {
acc[1].con[prop] = obj[0][prop];
}
return acc;
},
[{ emp: {} }, { con: {} }]
);
console.log(format(data));
答案 1 :(得分:1)
var item = {
"Emp_code": "EM-00001",
"Emp_title": "11",
"Emp_firstName": "22",
"Emp_lastName": "33",
"Emp_dateOfBirth": "20-10-1985",
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}
var data = [item, item];
var res = []
for (var item of data) {
var temp = {};
res.push(temp);
for (var prop in item) {
var parts = prop.split('_');
var prefix = parts[0].toLowerCase();
temp[prefix] = temp[prefix] || {};
temp[prefix][prefix === 'emp' ? parts[1] : prop] = item[prop]
}
}
console.log(res);
答案 2 :(得分:1)
下面的脚本使用循环检查元素,然后将其拆分为前缀和后缀。然后检查结果数组中是否存在前缀。如果不是,则将该前缀添加到数组中并准备结果。
var a = [{"Emp_code": "EM-00001", "Emp_title": "11", "Emp_firstName": "22", "Emp_lastName": "33", "Emp_dateOfBirth": "20-10-1985", "Con_title": "title", "Con_email": "email", "Con_addres": "address", "Con_phone": "phone"}];
var b = [];
$.each(a, function(arrKey, arrData){
var tempArr = {};
$.each(arrData, function(key, value){
var arrKey = key.split('_');
var prefix = arrKey[0];
var suffix = arrKey[1];
if( $.inArray(prefix, Object.keys(tempArr)) == -1 ) {
tempArr[prefix] = {};
}
tempArr[prefix][suffix]=value;
});
b.push(tempArr);
});
console.log(b);