Filter/Map/Reduce 正确
Filter/Map/Reduce properly
我正在尝试通过 JavaScript 的 filter
、map
和 reduce
方法过滤用户 JSON。但是我无法得到我假装的确切结果。
var users = {
"fooUser": {
"apps": [
{
"id": "7i2j3bk85"
},
{
"id": "o8yasg69h"
}
]
},
"barUser": {
"apps": [
{
"id": "789gbiai7t"
}
]
}};
逻辑是:我只知道 AppId(而不是它所属的用户),所以我必须 map/filter 每个用户,并且 return 只有当它有那个Appid(和 return 只有那个 AppId)。
var filteredApps = Object.keys(users).filter(function (element, index, array) {
var exists = users[element].apps.filter(function (element, index, array) {
if (element.id === 'o8yasg69h') {
return true;
} else {
return false;
}
});
if (exists[0]) {
return true;
} else {
return false;
}
}).map(function (item, index, array) {
return users[item].apps;
});
console.log(filteredApps);
我获得(一个没有过滤应用程序的多阵列):
[[
{
id: "7i2j3bk85"
},
{
id: "o8yasg69h"
}
]]
但我想获得(一个普通对象,带有过滤后的应用程序):
{
id: "o8yasg69h"
}
我会用 reduce
和 ES6 find
:
function searchById(id){
return Object.keys(users).reduce(function(result, user){
return result ? result : users[user].apps.find(function(obj){
return obj.id === id;
});
}, false);
}
您可以使用以下一行代码完成此操作:
[].concat(...Object.keys(users).map(x=> users[x].apps)).find(x=> x.id === "o8yasg69h")
扩展一下:
[].concat(... // flattens the array of apps
Object.keys(users) // gets the keys of users
.map(x=> users[x].apps) // maps the array to the apps of the user
).find(x=> x.id === "o8yasg69h") // finds app which id is "o8yasg69h"
我正在尝试通过 JavaScript 的 filter
、map
和 reduce
方法过滤用户 JSON。但是我无法得到我假装的确切结果。
var users = {
"fooUser": {
"apps": [
{
"id": "7i2j3bk85"
},
{
"id": "o8yasg69h"
}
]
},
"barUser": {
"apps": [
{
"id": "789gbiai7t"
}
]
}};
逻辑是:我只知道 AppId(而不是它所属的用户),所以我必须 map/filter 每个用户,并且 return 只有当它有那个Appid(和 return 只有那个 AppId)。
var filteredApps = Object.keys(users).filter(function (element, index, array) {
var exists = users[element].apps.filter(function (element, index, array) {
if (element.id === 'o8yasg69h') {
return true;
} else {
return false;
}
});
if (exists[0]) {
return true;
} else {
return false;
}
}).map(function (item, index, array) {
return users[item].apps;
});
console.log(filteredApps);
我获得(一个没有过滤应用程序的多阵列):
[[
{
id: "7i2j3bk85"
},
{
id: "o8yasg69h"
}
]]
但我想获得(一个普通对象,带有过滤后的应用程序):
{
id: "o8yasg69h"
}
我会用 reduce
和 ES6 find
:
function searchById(id){
return Object.keys(users).reduce(function(result, user){
return result ? result : users[user].apps.find(function(obj){
return obj.id === id;
});
}, false);
}
您可以使用以下一行代码完成此操作:
[].concat(...Object.keys(users).map(x=> users[x].apps)).find(x=> x.id === "o8yasg69h")
扩展一下:
[].concat(... // flattens the array of apps
Object.keys(users) // gets the keys of users
.map(x=> users[x].apps) // maps the array to the apps of the user
).find(x=> x.id === "o8yasg69h") // finds app which id is "o8yasg69h"