我有一个这样的对象数组
array = {
"microservices": [
{
"id": 1,
"permissions": [
{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [
{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
从微服务数组中,我只想获取“权限”数组并将其存储到一个新变量中,我进行了搜索,但没有任何相关的解决方案,在此先感谢
答案 0 :(得分:1)
您可以使用map
运算符并单独获取该特定属性。请检查下面的JS示例。
const array = {
"microservices": [{
"id": 1,
"permissions": [{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
const output = []
array.microservices.map(function(x) {
output.push(...x.permissions);
})
console.log(output);
答案 1 :(得分:1)
仅需按以下步骤迭代json对象。新数组“权限”将返回您的数据。
getPermissions(){
this.array.microservices.forEach(element => {
element.permissions.forEach(ele => {
this.permissions.push(ele);
});
});
console.log(this.permissions);
}
预先也可以使用.map运算符。
答案 2 :(得分:0)
这不是特定的Angular或Typescript问题,但是您可以这样做
const whatYouNeed = array.microservices.reduce((sum, item) => {
sum.push(item.permissions);
return sum;
}, []);
或者如果您希望它是一个级别:
const whatYouNeed = array.microservices.reduce((sum, item) => {
sum = sum.concat(item.permissions);
return sum;
}, []);
答案 3 :(得分:0)
由于您想要一个包含所有权限的数组,因此这是最干净的方法。了解flatMap here
const permissions = array.microservices.flatMap(i => i.permissions)
console.log(permissions);
使用polyfill获得浏览器支持。在上面的链接中可用。
答案 4 :(得分:0)
您可以使用ES6 map
。
const permissionsArrays = array.microservices.map(microservice => microservice.permissions)
答案 5 :(得分:0)
因此,假设这是您收到的json数据:
{
"microservices": [
{
"id": 1,
"permissions": [
{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [
{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
只需创建一个界面即可使用智能感知:
export interface Microservice {
microservices?: (MicroservicesEntity)[] | null;
}
export interface MicroservicesEntity {
id: number;
permissions?: (PermissionsEntity | null)[] | null;
}
export interface PermissionsEntity {
id: number;
name: string;
}
通过这种方式,您可以获得智能感知的帮助,因此可以通过引用json数据的接口来访问数据:
data: Microservice;
之后,使用地图获取权限数组
答案 6 :(得分:0)
首先,您有一个包含数组而不是实际数组的对象。但是让我们暂时忽略它。
array = {
"microservices": [
{
"id": 1,
"permissions": [
{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [
{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
const permissions = array.microservices.map(item => {
return item.permissions;
});