我有一个结构类似于下面;
var devices = {
'device-1' : {
'id' :'device1',
'template' :'template-1',
'user-1' :{
'name' : 'John Doe',
'authority' : 'author1',
},
'admin-1' :{
'name' : 'Bob Doe',
'authority' : 'author2',
},
'user-35' :{
'name' : 'Bill Doe',
'authority' : 'author1',
},
'author-42' :{
'name' : 'Jack Doe',
'authority' : 'author1|author3',
}
},
'device-2' : {
'id' :'device2',
'template' :'template-2',
'some-27' :{
'name' : 'John Doe',
'authority' : 'author1',
},
'other-42' :{
'name' : 'Jack Doe',
'authority' : 'author2',
}
},
'device-7' : {
'id' :'device7',
'template' :'template-1',
'user-2' :{
'name' : 'Samantha Doe',
'authority' : 'author2',
}
'admin-40' :{
'name' : 'Marry Doe',
'authority' : 'author1',
},
}
};我希望通过过滤用户x元素的“属性值”值来获取它们的所有“值”条目。
例如:
我希望根据用户的“权限”属性过滤用户的所有名称(不管是在哪个设备中,这些用户if是什么),如果我希望筛选'author1‘权限’,那么我就可以获得在任何设备上有'author1‘权限的用户。
我检查了许多地方(包括StackOverflow),但大多数示例都局限于二维对象数组、变量是特定的或对象是基于整数的(如=>数组)。
但是在这个例子中,'device-x'和'user-x'条目是不确定的(所以我不能说它们的值是这些),但是'name'和'authority'键是确定的(由系统分配),并且这些变量的计数可以改变(crud操作)。
现在就谢了。
UPDATE:由于我的假设错误(我认为如果我编写的user部件彼此不同,人们认为这些值不遵循任何规则)问题并不清楚。所以我编辑了代码。最后:“名称”和“权威”键值对的所有者是用户名,它们是用户定义的。
因此,所有的设备对象都将有id、模板、未知用户字段,但所有未知用户字段都必须具有'name‘和'authority’键值对。
发布于 2017-09-02 13:26:38
使用reduce & filter & map。
更新了:我添加了一个isLikeUserObj函数,用于name & authority字段。
const devices = {
'device-1': {
'id': 'device1',
'template': 'template-1',
'user-1': {
'name': 'John Doe',
'authority': 'author1',
},
'admin-1': {
'name': 'Bob Doe',
'authority': 'author2',
},
'user-35': {
'name': 'Bill Doe',
'authority': 'author1',
},
'author-42': {
'name': 'Jack Doe',
'authority': 'author1|author3',
}
},
'device-2': {
'id': 'device2',
'template': 'template-2',
'some-27': {
'name': 'John Doe',
'authority': 'author1',
},
'other-42': {
'name': 'Jack Doe',
'authority': 'author2',
}
},
'device-7': {
'id': 'device7',
'template': 'template-1',
'user-2': {
'name': 'Samantha Doe',
'authority': 'author2',
},
'admin-40': {
'name': 'Marry Doe',
'authority': 'author1',
},
}
};
const result = getUserByAuthority('author3');
function getUserByAuthority(requiredAuth) {
return Object.keys(devices).reduce((result, deviceKey) => {
const users = Object.keys(devices[deviceKey])
.filter((key) => isUserLikeObj(devices[deviceKey][key]))
.map(userKey => devices[deviceKey][userKey])
.filter((user) => user.authority.split('|').indexOf(requiredAuth) > -1)
.map((user) => user.name)
return result.concat(users);
}, [])
}
function isUserLikeObj(value) {
return typeof value === 'object' && value.hasOwnProperty('name') && value.hasOwnProperty('authority')
}
console.log(result)
发布于 2017-09-02 12:47:46
您可以使用for-in循环遍历对象.以下方法可以满足您的需要
const result = []
for (let i in devices) {
for (let j in devices[i]) {
if (/user-\d+/.test(j)) {
if (devices[i][j].authority.split('|').indexOf('author1') !== -1) {
result.push(devices[i][j].name)
}
}
}
}
console.log(result)https://stackoverflow.com/questions/46013639
复制相似问题