【问题标题】:Filter/Map/Reduce properly过滤/映射/减少正确
【发布时间】:2016-06-28 14:24:17
【问题描述】:

我正在尝试通过 JavaScript 的 filtermapreduce 方法过滤用户 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


【解决方案1】:

我会使用 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);
}

【讨论】:

    【解决方案2】:

    您可以使用以下单线来做到这一点:

    [].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"
    

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2018-07-13
      • 2010-10-23
      • 1970-01-01
      • 2020-05-07
      相关资源
      最近更新 更多