假设一个 api 正在返回 apiResult
中的结构,我想创建一个两级索引来查找给定作者对给定文章的评论。
作者、文章和评论的查找表本身很简单,但我在 CommentsByArticleAndAuthor
查找表上遇到了困难。
在 mapped
结构中,我展示了我如何为三个“简单”部分制作查找索引,以及我如何希望 CommentsByArticleAndAuthor
看。
我怎样才能继续生成这个索引?
var apiResult = {
Authors: [
{
Id: "author-id-1",
Name: "Author One"
},
{
Id: "author-id-2",
Name: "Author Two"
}
],
Articles: [
{
Id: "article-id-1",
Title: "This Great Article"
}
],
Comments: [
{
Id: "comment-id-1",
AuthorId: "author-id-1",
ArticleId: "article-id-1",
Comment: "that great, hu?"
},
{
Id: "comment-id-2",
AuthorId: "author-id-2",
ArticleId: "article-id-1",
Comment: "yes, that great"
}
]
}
var mapped = {
Authors: _.keyBy(apiResult.Authors, 'Id'),
Articles: _.keyBy(apiResult.Articles, 'Id'),
Comments: _.keyBy(apiResult.Comments, 'Id'),
CommentsByArticleAndAuthor: {
"article-id-1": {
"author-id-1": [ "comment-id-1" ],
"author-id-2": [ "comment-id-2" ]
}
}
}
console.log(JSON.stringify(mapped, null, 2));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
最佳答案
您可以迭代评论并构建分层对象结构。
var apiResult = { Authors: [{ Id: "author-id-1", Name: "Author One" }, { Id: "author-id-2", Name: "Author Two" }], Articles: [{ Id: "article-id-1", Title: "This Great Article" }], Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" }, { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }] },
mapped = { CommentsByArticleAndAuthor: {} };
apiResult.Comments.forEach(function (o) {
var ref = mapped.CommentsByArticleAndAuthor;
ref[o.ArticleId] = ref[o.ArticleId] || {};
ref[o.ArticleId][o.AuthorId] = ref[o.ArticleId][o.AuthorId] || [];
ref[o.ArticleId][o.AuthorId].push(o.Id);
});
console.log(mapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
对于更动态的方法,您可以为层次结构使用数组,为默认值使用对象。
var apiResult = { Authors: [{ Id: "author-id-1", Name: "Author One" }, { Id: "author-id-2", Name: "Author Two" }], Articles: [{ Id: "article-id-1", Title: "This Great Article" }], Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" }, { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }] },
mapped = { CommentsByArticleAndAuthor: {} };
apiResult.Comments.forEach(function (o) {
['ArticleId', 'AuthorId'].reduce(function (r, k) {
return r[o[k]] = r[o[k]] || { AuthorId: [] }[k] || {};
}, mapped.CommentsByArticleAndAuthor).push(o.Id);
});
console.log(mapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 使用lodash创建多级查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44391097/