【发布时间】:2020-12-04 02:46:17
【问题描述】:
我正在尝试将数组与分配的属性进行比较,我只能使用高阶函数(.map()、.filter()、.forEach()、.some() 等...) .数组是“userWishlist”,属性来自“parks”数组“parks[index].id”的对象中的 ID。有人对解决此类问题有什么建议吗?我的代码现在只返回:
[{"id":1,"name":"Acadia","areaInSquareKm":198.6,"location":{"state":"Maine"}}]
调用时:
getWishlistParksForUser(parks, users, "dwayne.m55")
为什么我的代码不会返回与“愿望清单”数组匹配的所有“公园”对象?
/* Function should compare the user's wishlist with the parks */
function getWishlistParksForUser(parks, users, userID) {
let wishArray = [];
// Find the user
const findUser = Object.keys(users).filter(user => user == userID);
// Create array out of wishlist
const userWishlist = users[findUser].wishlist.map(list => list);
// Compare the two arrays and push park into wishlist array
const parkID = userWishlist.forEach((wish, index) => {
if (wish === parks[index].id) wishArray.push(parks[index])
})
return wishArray;
}
// The users objects (non-editable)
const users = {
"karah.branch3": {
visited: [2],
wishlist: [1, 3],
},
"dwayne.m55": {
visited: [2, 3],
wishlist: [1, 3],
},
};
// The parks array (non-editable)
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: "Zion",
areaInSquareKm: 595.9,
location: {
state: "Utah"
},
},
];
console.log(getWishlistParksForUser(parks, users, "dwayne.m55"));
【问题讨论】:
-
“从愿望清单中创建数组”。已经是数组了,为什么还要用
map()做成数组呢? -
findUser只是一个包含userID的数组。那有什么意义呢?为什么使用数组作为对象属性?只需使用users[userID].wishlist。
标签: javascript arrays object properties higher-order-functions