这是我的JSON数据输入。
"rows": [
[
1,
"GESTORE_PRATICHE",
1,
"GESTORE PRATICHE",
"canViewFolderManagement"
],
[
2,
"ADM",
1,
"AMMINISTRATORE",
"canViewFolderManagement"
],
[
2,
"ADM",
2,
"AMMINISTRATORE",
"canViewOther"
]
]
我需要使用下面的下划线来获得一个新的JSON:
[
{
"groupID": "1",
"groupName":"GESTORE_PRATICHE",
"groupDescr":"GESTORE PRATICHE",
"functionList": [
{
"1": "canviewfoldermanagement"
}
]
},
{
"groupID": "2",
"groupName":"ADM",
"groupDescr":"AMMINISTRATORE",
"functionList": [
{
"1": "canviewfoldermanagement",
"2": "canviewOther"
}
]
}
]
所以我需要一个对象数组,其中包含按ID分组的单个元素(每个元素的第一个键)。我尝试使用下划线js过滤器,groupby函数,但我到目前为止......
我在角度2中的尝试之一:
constructor(private sanitizer: DomSanitizer, private http: Http) {
this.source = new LocalDataSource(this.data); // create the source ;
this.http.get('app/json/profileInput.json')
.subscribe(res => this.data = res.json());
let profileInput;
this.http.get('app/json/profileInput.json')
.subscribe(res =>{
profileInput = res.json()
//console.log(JSON.stringify(profileInput));
this.profileConstructor(profileInput.rows);
}
);
}
profileConstructor(profileRows){
console.log(JSON.stringify(
_.object(JSON.stringify([_.object([profileRows], ['riga'])], [1, 2, 3, 4, 5]))
)
);
} ;
答案 0 :(得分:1)
使用数组reduce()
函数,您可以轻松地将现有数组转换为具有所需值的对象。
reduce
有两个参数
第一个参数:要返回的新变量(可以是对象,数组或任何其他类型)
第二个参数:数组的项目。
arr = [
[
1,
"GESTORE_PRATICHE",
1,
"GESTORE PRATICHE",
"canViewFolderManagement"
],
[
2,
"ADM",
1,
"AMMINISTRATORE",
"canViewFolderManagement"
],
[
2,
"ADM",
2,
"AMMINISTRATORE",
"canViewOther"
]
]
arr = arr.reduce((a, b) => {
let flag = false,
obj = {};
a.forEach(item => {
if (item.groupID === b[0] && item.groupName === b[1] && item.groupDescr === b[3]) {
item.functionList[0][b[2]] = b[4];
flag = true;
}
});
if (!flag) {
obj[b[2]] = b[4];
a.push({
"groupID": b[0],
"groupName": b[1],
"groupDescr": b[3],
"functionList": [obj]
});
}
return a;
}, []);
console.log(arr);

答案 1 :(得分:1)
如果没有组,您可以使用Map
并创建新条目。
function group(array) {
var map = new Map;
array.forEach(function (o) {
var group = map.get(o[0]) || { groupID: o[1], groupName: o[1], groupDescr: o[3], functionList: {} };
if (!map.has(o[0])) {
map.set(o[0], group);
}
group.functionList[o[2]] = o[4];
});
return [...map.values()];
}
var rows = [[1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement"], [2, "ADM", 1, "AMMINISTRATORE", "canViewFolderManagement"], [2, "ADM", 2, "AMMINISTRATORE", "canViewOther"]],
result = group(rows);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }