javascript - 通过 id 从对象中获取数据
问题描述
这是代码
该peeps
对象具有像“Deen”这样的人物细节:
const peeps = {
1: {
id: 1,
name: 'Deen',
readerCategory: 'champ',
},
.
.
.
};
并且该chart
数组结合了哪些窥视和喜欢的书 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
属性返回一个相关的字符串。
如果您需要一些文档,那么我建议您看一下这样的东西,其余的应该相对简单。
编辑
如果您想了解更多关于我决定使用的语法,它被称为柯里化,如果您想了解更多关于柯里化和函数式编程等主题的信息,那么Eric的帖子将是一个极好的信息来源. 我发现 Eric 是学习如何在 JavaScript 应用程序中实现函数式编程的绝佳来源。
编辑 2
根据要求喜欢同一本书的人,正如您在此示例中看到的那样,该函数还有一个参数,它只接受您正在查询的书名。然后,此函数将使用该reduce
函数生成一个名称数组,如 book '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'));
推荐阅读
- amazon-web-services - 通过 route53 的 API 网关给出 403 Forbidden
- sql - 如何计算矩阵中NULL值的比例?
- laravel - Laravel 与 PhpStorm,找不到方法 findOrFail
- analytics - 类别占 Cognos 表达式构建器总数的百分比
- charts - 如何在 Charts 框架或任何其他框架替代方案的帮助下使用 SwiftUI 在 Widget 上绘制图表?
- visual-studio - FTPS ClickOnce 在 Visual Studio 2019 中发布
- python - Plotly Express 等值线图未显示在 Visual Studio 代码中
- anychart - 使用 React 的 Anychart 绘图和注释
- c# - 根据消息元数据过滤 ServiceBusTrigger 消息
- powershell - 将 Powershell 输出转换为 Markdown 文件