目前我有一个包含多个数据的json文件,如下所示:
{"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"]}
该行应该代表大学(因此名称),“name”之后的变量,即“supp”,“online”等,是该学校的属性。如何重构此数据以使“name”变量定义数据,其他变量为“name”parent的cildren。我的数据应如下所示:
{
"schools": {
"Adelphi University": {
"supp": "Yes: E, WS",
"ed": "\u00a0",
"online": "$40",
"ea": "12/1",
"mid": "No",
"rd": "Rolling",
"recs": "Yes: CR",
"mail": "$40",
"schoolr": "Yes",
},
"Dartmouth College": { ... },
"Harvard University": { ... }
}
}
我将如何做到这一点?
答案 0 :(得分:2)
您可以迭代密钥并测试name
,然后使用名称构建对象并分配临时对象。否则确定价值。
var array = [{ "name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"] }, { "name": ["Dartmouth College"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"] }],
schools = {},
result = { schools: schools };
array.forEach(function (a) {
var temp = {};
Object.keys(a).forEach(function (k) {
if (k === 'name') {
schools[a[k][0]] = temp;
return;
}
temp[k] = a[k][0];
});
});
console.log(JSON.stringify(result));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
假设您显示的对象是一个看起来相同的事物数组中的一条记录,您可以这样做:
var schoolArray = [/** your current json structure **/];
var schools = {};
schoolArray.forEach(function(item) {
//probably want to test for existence here, just in case
var name = item.name[0];
schools[name] = {};
delete item.name;
Object.keys(item).forEach(function(key) {
// again, testing for existence on the right hand side woudl be a good idea.
schools[name][key] = item[key][0];
});
});
console.log({ schools : schools }); // should be the structure you asked for.