【问题标题】:function that returns object names返回对象名称的函数
【发布时间】:2021-06-28 22:18:08
【问题描述】:
const parks = [
    {
      id: 1,
      name: "Acadia",
      areaInSquareKm: 198.6,
      location: { state: "Maine" },
    },
    {
      id: 2,
      name: "Canyonlands",
      areaInSquareKm: 1366.2,
      location: { state: "Utah" },
    },
    {
      id: 3,
      name: "Crater Lake",
      areaInSquareKm: 741.5,
      location: { state: "Oregon" },
    },
    {
      id: 4,
      name: "Lake Clark",
      areaInSquareKm: 10602,
      location: { state: "Alaska" },
    },
    {
      id: 5,
      name: "Kenai Fjords",
      areaInSquareKm: 2710,
      location: { state: "Alaska" },
    },
    {
      id: 6,
      name: "Zion",
      areaInSquareKm: 595.9,
      location: { state: "Utah" },
    },
  ];

  const users = {
    "karah.branch3": {
      visited: [1],
      wishlist: [4, 6],
    },
    "dwayne.m55": {
      visited: [2, 5, 1],
      wishlist: [],
    },
    thiagostrong1: {
      visited: [5],
      wishlist: [6, 3, 2],
    },
    "don.kim1990": {
      visited: [2, 6],
      wishlist: [1],
    },
  };

我需要创建一个函数来执行此操作:此函数返回访问过给定用户愿望清单中任何公园的所有用户名。

getUsersForUserWishlist(users, "karah.branch3"); //> ["dwayne.m55"]
getUsersForUserWishlist(users, "dwayne.m55"); //> []

这是我目前所拥有的,但它不起作用:

function getUsersForUserWishlist(users, userId) {
  let wish = userId.wishlist;
  return users[userId].visited.map((visited) => wish.includes(visited));
}

请记住:我刚刚完成了课程的一部分,涵盖了高级功能(find、filter、map、some、every、forEach),我应该使用它们来解决问题。

【问题讨论】:

  • 我很难看到这里的逻辑。你能解释一下为什么["dwayne.m55"]karah.branch3 的预期输出吗?根据您对函数“此函数返回访问给定用户愿望清单中任何公园的所有用户名”功能的描述,我希望它是["don.kim1990"],因为 dom.kim1990 访问了 Karah 愿望清单中的公园 6

标签: javascript arrays function javascript-objects higher-order-functions


【解决方案1】:

让我们回顾一下你尝试过的内容:

let wish = userId.wishlist;

这里,userId 是一个字符串。字符串没有属性wishlist。您需要获取与该 ID 对应的用户对象:users[userId].wishlist。就像你在第二行所做的那样:

users[userId].visited.map((visited) => wish.includes(visited));

但是,map 并不是您想要实现的最佳方法。您希望filter 用户名仅保留通过条件的用户名。即愿望清单中的some 公园在该用户访问的公园列表中是included

const users= {
  "karah.branch3": { visited: [1], wishlist: [4,6] },
  "dwayne.m55": { visited: [2,5,1], wishlist: [] },
  "thiagostrong1": { visited: [5], wishlist: [6,3,2] },
  "don.kim1990": { visited: [2,6], wishlist: [1] }
};

function getUsersForUserWishlist(users, userId) {
  const wishlist = users[userId].wishlist;
  // Get all user names
  return Object.keys(users)
    // Filter them
    .filter(
      // If the wishlist has some elements which that user has visited
      name => wishlist.some(park => users[name].visited.includes(park))
    );
}

console.log(getUsersForUserWishlist(users, "karah.branch3")); //> ["don.kim1990"]
console.log(getUsersForUserWishlist(users, "dwayne.m55")); //> []

【讨论】:

  • 啊,非常感谢!我已经忘记了 Object.keys()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多