【发布时间】:2016-06-28 14:24:17
【问题描述】:
我正在尝试通过 JavaScript 的 filter、map 和 reduce 方法过滤用户 JSON。但是我无法得到我假装的确切结果。
var users = {
"fooUser": {
"apps": [
{
"id": "7i2j3bk85"
},
{
"id": "o8yasg69h"
}
]
},
"barUser": {
"apps": [
{
"id": "789gbiai7t"
}
]
}};
逻辑是:我只知道 AppId(而不是它所属的用户),所以我必须映射/过滤每个用户,并且只有当它有那个 Appid 时才返回它(并且只返回那个 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);
我获得(一个没有过滤应用的 multiArray):
[[
{
id: "7i2j3bk85"
},
{
id: "o8yasg69h"
}
]]
但我想获得(一个普通的对象,带有过滤的应用程序):
{
id: "o8yasg69h"
}
【问题讨论】:
-
“但我想获得(一个普通对象,带有过滤的应用程序):” 预期结果是具有单个属性的对象吗?
-
获取
exists我认为你应该使用.some()而不是.filter()。 -
仅用于检查对象中是否存在
'o8yasg69h'值 - 上面的代码是多余的
标签: javascript mapping filtering reduce