本文介绍了类似于 Javascript 对象的 SQL“JOIN"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于表示为 Javascript 对象数组的表,什么是 SQL 'JOIN' 的实用类比?Javascript Array.join 和 D3.js 'd3.merge` 不是同一个概念.

What's a pragmatic analog to SQL 'JOIN' for tables represented as arrays of Javascript objects? Javascript Array.join and D3.js 'd3.merge` are not the same concept.

例如SELECT * FROMauthors LEFT JOIN 书籍 ONauthors.id = books.author_id?

第一张桌子:

var authors =
[  { id: 1, name: 'adam'},
   { id: 2, name: 'bob'},
   { id: 3, name: 'charlie'}, ...
]

第二个表:

var books =
[  { author_id: 1, title: 'Coloring for beginners'},
   { author_id: 1, title: 'Advanced coloring'},
   { author_id: 2, title: '50 Hikes in New England'},
   { author_id: 2, title: '50 Hikes in Illinois'},
   { author_id: 3, title: 'String Theory for Dummies'}, ...
]

表格是使用 D3.js 从 CSV 加载的.

The tables are loaded from CSV using D3.js d3.csv(), so have D3.js already, open to other libs but generally prefer coding directly if not too far out of the way.

我看到 在 Javascript 中合并对象的本机方式,它使用RethinkDB,在这方面似乎有些过头了,但这就是想法.

I see Native way to merge objects in Javascript which uses RethinkDB, which seems over the top for this, but this is the idea.

推荐答案

基本上是这样的:

// first, build an easier lookup of author data:
var authormap = {};
authors.forEach(function(author) {authormap[author.id] = author;});

// now do the "join":
books.forEach(function(book) {
    book.author = authormap[book.author_id];
});

// now you can access:
alert(books[0].author.name);

这篇关于类似于 Javascript 对象的 SQL“JOIN"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 19:12