本文介绍了对于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 * FROM authors LEFT JOIN books ON authors.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从CSV加载表格.js d3.csv(),所以D3.js已经开放给其他库,但是如果不是太远的话,通常更喜欢编码。

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.

我看到中,这似乎是最重要的,但这是主意。

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