这是代码
peeps
对象具有像“Deen”这样的人员详细信息:
const peeps = {
1: {
id: 1,
name: 'Deen',
readerCategory: 'champ',
},
.
.
.
};
chart
数组包含 which peeps 和喜欢的图书 ID 的组合:
const chart = [
{
id: 1,
peepsID: '1',
bookLikedID: '1',
},
.
.
.
];
books
对象有像“哈利波特系列”这样的书名:
const books = {
1: {
id: 1,
name: 'Harry Potter Series',
},
根据此信息,其中一个列表项可能如下所示:
* Deen's likes a Harry Potter Series book.
最佳答案
你总是可以这样做,如你所见,我们只是遍历 chart
数组,获取相关的 id
,并根据bookLikedID
、peepsID
和 name
属性。
如果您需要一些文档,那么我建议您看一下类似 this 的内容,其余的应该相对简单。
编辑
如果您想了解更多关于我决定使用的语法,它被称为 currying,如果您想阅读更多关于 currying 和函数式编程等主题,那么一个很好的信息来源将是Eric 的帖子.我发现 Eric 是学习如何在 JavaScript 应用程序中实现函数式编程的极好来源。
编辑2
按要求喜欢同一本书的人,正如您在本例中看到的那样,该函数还接受一个参数,它只接受您要查询的书名。然后此函数将使用 reduce
函数生成一组类似于书“x”的名称。
我也用过 Object.keys
和 Object.values
用于更新以查找所有喜欢 'x'
书的人。
const peeps={1:{id:1,name:"Deen",readerCategory:"champ"},2:{id:2,name:"Tom",readerCategory:"noob"},3:{id:3,name:"Jack",readerCategory:"GOD"}};
const chart=[{id:1,peepsID:"1",bookLikedID:"1"},{id:2,peepsID:"2",bookLikedID:"1"},{id:3,peepsID:"3",bookLikedID:"2"}];
const books={1:{id:1,name:"Harry Potter Series"},2:{id:2,name:"Lord Of The Rings Series"},3:{id:3,name:"Fifty Shades of Grey"}};
// Edit
const results = a => b => c => a.map(o => `${b[o.peepsID].name} likes ${c[o.bookLikedID].name}`);
// Edit 2
const similarTastes = a => b => c => n => a.reduce((v, o) => {
const found = Object.values(c).find(({name}) => name == n);
if (found && o.bookLikedID == found.id) v.push(b[o.peepsID].name);
return v;
}, []);
// Edit 3
const getAllSimilarTastes = a => b => c => {
const obj = {};
Object.keys(c).map(k => obj[c[k].name] = similarTastes(a)(b)(c)(c[k].name));
return obj;
};
// Edit 4
const getUnliked = a => b => c => {
const o = getAllSimilarTastes(a)(b)(c);
return Object.keys(o).filter(x => o[x].length <= 0);
};
const isUnliked = a => b => c => n => getUnliked(a)(b)(c).indexOf(n) >= 0;
// Results.
console.log(results(chart)(peeps)(books));
console.log(similarTastes(chart)(peeps)(books)('Harry Potter Series'));
console.log(getAllSimilarTastes(chart)(peeps)(books));
console.log(getUnliked(chart)(peeps)(books));
console.log(isUnliked(chart)(peeps)(books)('Fifty Shades of Grey'));
console.log(isUnliked(chart)(peeps)(books)('Harry Potter Series'));
关于javascript - 通过对象的id获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54125802/