有什么方法可以“加入”两个 javascript 数组的内容,就像我在 SQL 中加入一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17500312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there some way I can "join" the contents of two javascript arrays much like I would do a join in SQL
提问by Alan2
I have two arrays: Question and UserProfile
我有两个数组: Question 和 UserProfile
- The
userProfiles
: [] array contain{ id, name }
objects - The
questions
: [] array contains{ id, text, createdBy }
objects
- 的
userProfiles
:[]数组包含{ id, name }
对象 - 的
questions
:[]数组包含{ id, text, createdBy }
对象
The createdBy
integer in questions is always one of the id values in userProfiles
.
createdBy
问题中的整数始终是 中的 id 值之一userProfiles
。
Is there a way I could "join" the arrays in much the same way as I would join up two SQL tables if I was using a database.
有没有一种方法可以“连接”数组,就像使用数据库时连接两个 SQL 表一样。
What I need as an end result is an array that contains
我需要的最终结果是一个包含
{ id, text, name }
采纳答案by Joseph Myers
This seems to be an important general-purpose question, and although there are many answers, some have borderline behavior like modifying the existing data, solving a completely different problem than the issue at hand, using up to 93,057 bytes of JavaScript (not to mention producing the wrong result), producing overly complex additional nesting of data structures, requiring a lot of code on each invocation, and most seriously, not being a self-contained solution to the important more general-purpose problem at the heart of this question.
这似乎是一个重要的通用问题,虽然有很多答案,但有些具有边缘行为,例如修改现有数据,解决与手头问题完全不同的问题,使用高达 93,057 字节的 JavaScript(更不用说产生错误的结果),产生过于复杂的额外数据结构嵌套,每次调用都需要大量代码,最严重的是,它不是解决这个问题核心的更重要的通用问题的独立解决方案。
So for better or for worse, I wrote a shim that extends the JavaScript Array
object with a method .joinWith
intended to be used in order to join this
array of objects with that
array of objects, by
a common indexing field. It is possible to select
a list of fields desired in output (good for merging arrays of objects with many fields when only a few are wanted) or to omit
a list of fields in output (good for merging arrays of objects when most fields are desired but a few are not).
因此,无论好坏,我编写了一个 shim,它Array
使用一种方法扩展 JavaScript对象,该方法.joinWith
旨在用于将this
对象that
数组与对象数组(by
一个常见的索引字段)连接起来。它可以select
输出所需的(好时,只有少数是想合并与许多领域对象数组)的字段列表或omit
域的输出(名单利于合并对象的数组时,大部分的项目是需要的,但一少数不是)。
The shim code isn't made to look pretty, so it will be at the end, with the example of how to use it for the OP's particular kind of data coming first:
填充代码看起来并不漂亮,所以它会放在最后,首先是如何将它用于 OP 的特定类型的数据的示例:
/* this line will produce the array of objects as desired by the OP */
joined_objects_array = userProfiles.joinWith(questions, 'id', ['createdBy'], 'omit');
/* edit: I just want to make 100% sure that this solution works for you, i.e.,
* does exactly what you need. I haven't seen your actual data, so it's
* possible that your IDs are are not in common, (i.e., your createdBy
* is in common like you said, but not the IDs, and if so you could
* morph your data first like this:
* questions.map(function(x) { x.id = x.createdBy; });
* before joining the arrays of objects together.
*
*/
The following code is for demonstration:
以下代码用于演示:
var array1 = [{ id: 3124, name: 'Mr. Smith' },
{ id: 710, name: 'Mrs. Jones' }];
var array2 = [{ id: 3124, text: 'wow', createdBy: 'Mr. Jones' },
{ id: 710, text: 'amazing' }];
var results_all = array1.joinWith(array2, 'id');
// [{id:3124, name:"Mr. Smith", text:"wow", createdBy:"Mr. Jones"},
// {id:710, name:"Mrs. Jones", text:"amazing"}]*
var results_selected = array1.joinWith(array2, 'id', ['id', 'text', 'name']);
// [{id:3124, name:"Mr. Smith", text:"wow"},
// {id:710, name:"Mrs. Jones", text:"amazing"}]*
/* or equivalently, */
var results_omitted = array1.joinWith(array2, 'id', ['createdBy'], 1);
// [{id:3124, name:"Mr. Smith", text:"wow"},
// {id:710, name:"Mrs. Jones", text:"amazing"}]*
There are some other nice things this solution does (one of them is preserving the ability to access the resulting data by its indexing key, despite returning an array).
这个解决方案还有一些其他的好处(其中之一是保留通过索引键访问结果数据的能力,尽管返回一个数组)。
Enjoy!
享受!
/* Array.joinWith - shim by Joseph Myers 7/6/2013 */
if (!Array.prototype.joinWith) {
+function () {
Array.prototype.joinWith = function(that, by, select, omit) {
var together = [], length = 0;
if (select) select.map(function(x){select[x] = 1;});
function fields(it) {
var f = {}, k;
for (k in it) {
if (!select) { f[k] = 1; continue; }
if (omit ? !select[k] : select[k]) f[k] = 1;
}
return f;
}
function add(it) {
var pkey = '.'+it[by], pobj = {};
if (!together[pkey]) together[pkey] = pobj,
together[length++] = pobj;
pobj = together[pkey];
for (var k in fields(it))
pobj[k] = it[k];
}
this.map(add);
that.map(add);
return together;
}
}();
}
Documentation:
文档:
/* this and that both refer to an array of objects, each containing
object[by] as one of their fields */
/*
N.B. It is the responsibility of the user of this method
to ensure that the contents of the [by] fields are
consistent with each other between the two arrays!
*/
/* select is an array of field names to be included in the resulting
objects--all other fields will be excluded, or, if the Boolean value
of omit evaluates to true, then select is an array of field names to
be excluded from the resulting objects--all others will be included.
*/
回答by Aadit M Shah
I think what you want is an inner join, which is simple enough to implement in JavaScript:
我认为你想要的是一个内部连接,它很简单,可以在 JavaScript 中实现:
const innerJoin = (xs, ys, sel) =>
xs.reduce((zs, x) =>
ys.reduce((zs, y) => // cartesian product - all combinations
zs.concat(sel(x, y) || []), // filter out the rows and columns you want
zs), []);
For the purpose of demonstration we'll use the following data set (thank you @AshokDamani):
出于演示目的,我们将使用以下数据集(谢谢@AshokDamani):
const userProfiles = [
{id: 1, name: "Ashok"},
{id: 2, name: "Amit"},
{id: 3, name: "Rajeev"},
];
const questions = [
{id: 1, text: "text1", createdBy: 2},
{id: 2, text: "text2", createdBy: 2},
{id: 3, text: "text3", createdBy: 1},
{id: 4, text: "text4", createdBy: 2},
{id: 5, text: "text5", createdBy: 3},
{id: 6, text: "text6", createdBy: 3},
];
This is how you would use it:
这是你将如何使用它:
const result = innerJoin(userProfiles, questions,
({id: uid, name}, {id, text, createdBy}) =>
createdBy === uid && {id, text, name});
In SQL terms this would be similar to:
在 SQL 术语中,这类似于:
SELECT questions.id, questions.text, userProfiles.name
FROM userProfiles INNER JOIN questions
ON questions.createdBy = userProfiles.id;
Putting it all together:
把它们放在一起:
const innerJoin = (xs, ys, sel) =>
xs.reduce((zs, x) =>
ys.reduce((zs, y) => // cartesian product - all combinations
zs.concat(sel(x, y) || []), // filter out the rows and columns you want
zs), []);
const userProfiles = [
{id: 1, name: "Ashok"},
{id: 2, name: "Amit"},
{id: 3, name: "Rajeev"},
];
const questions = [
{id: 1, text: "text1", createdBy: 2},
{id: 2, text: "text2", createdBy: 2},
{id: 3, text: "text3", createdBy: 1},
{id: 4, text: "text4", createdBy: 2},
{id: 5, text: "text5", createdBy: 3},
{id: 6, text: "text6", createdBy: 3},
];
const result = innerJoin(userProfiles, questions,
({id: uid, name}, {id, text, createdBy}) =>
createdBy === uid && {id, text, name});
console.log("Open your browser console to see the output.");
console.table(result);
Edit:However this is not the best solution. Since the above solution loops through the Cartesian productit takes O(m × n)
time to run. With a little bit of modification we can make it run in O(m + n)
time - @pebbl found it first:
编辑:但这不是最好的解决方案。由于上述解决方案循环通过笛卡尔积,因此O(m × n)
运行需要时间。通过一些修改,我们可以让它及时运行O(m + n)
- @pebbl 首先找到它:
const equijoin = (xs, ys, primary, foreign, sel) => {
const ix = xs.reduce((ix, row) => // loop through m items
ix.set(row[primary], row), // populate index for primary table
new Map); // create an index for primary table
return ys.map(row => // loop through n items
sel(ix.get(row[foreign]), // get corresponding row from primary
row)); // select only the columns you need
};
Now you could use it as follows:
现在您可以按如下方式使用它:
const result = equijoin(userProfiles, questions, "id", "createdBy",
({name}, {id, text}) => ({id, text, name}));
Putting it all together:
把它们放在一起:
const equijoin = (xs, ys, primary, foreign, sel) => {
const ix = xs.reduce((ix, row) => ix.set(row[primary], row), new Map);
return ys.map(row => sel(ix.get(row[foreign]), row));
};
const userProfiles = [
{id: 1, name: "Ashok"},
{id: 2, name: "Amit"},
{id: 3, name: "Rajeev"},
];
const questions = [
{id: 1, text: "text1", createdBy: 2},
{id: 2, text: "text2", createdBy: 2},
{id: 3, text: "text3", createdBy: 1},
{id: 4, text: "text4", createdBy: 2},
{id: 5, text: "text5", createdBy: 3},
{id: 6, text: "text6", createdBy: 3},
];
const result = equijoin(userProfiles, questions, "id", "createdBy",
({name}, {id, text}) => ({id, text, name}));
console.log("Open your browser console to see the output.");
console.table(result);
回答by Pebbl
If it were me, I'd approach this in the following manner:
如果是我,我会通过以下方式解决这个问题:
The set-up:
设置:
var userProfiles = [], questions = [];
userProfiles.push( {id:1, name:'test'} );
userProfiles.push( {id:2, name:'abc'} );
userProfiles.push( {id:3, name:'def'} );
userProfiles.push( {id:4, name:'ghi'} );
questions.push( {id:1, text:'monkey', createdBy:1} );
questions.push( {id:2, text:'Monkey', createdBy:1} );
questions.push( {id:3, text:'big', createdBy:2} );
questions.push( {id:4, text:'string', createdBy:2} );
questions.push( {id:5, text:'monKey', createdBy:3} );
First, would be to create a look-up object, where the linking id is used as a key
首先,将创建一个查找对象,其中链接 id 用作键
var createObjectLookup = function( arr, key ){
var i, l, obj, ret = {};
for ( i=0, l=arr.length; i<l; i++ ) {
obj = arr[i];
ret[obj[key]] = obj;
}
return ret;
};
var up = createObjectLookup(userProfiles, 'id');
Now that you have this, it should be easy to step through the questions, and find your user object to merge:
现在你有了这个,应该很容易逐步完成问题,并找到要合并的用户对象:
var i, l, question, user, result = [];
for ( i=0, l=questions.length; i<l; i++ ) {
if ( (question = questions[i]) && (user = up[question.createdBy]) ) {
result.push({
id: question.id,
text: question.text,
name: user.name
});
}
}
You should now have everything you need in result
你现在应该拥有你需要的一切 result
console.log(result);
回答by Anton
i just about always use underscore.js because it has such good support for arrays and "map reduce" which this problem can be solved with.
我几乎总是使用 underscore.js 因为它对数组和“map reduce”有很好的支持,可以解决这个问题。
here is a fiddle with a solution for your question ( it assumes there is only one question per user as your original post suggests)
这是针对您的问题的解决方案(假设每个用户只有一个问题,正如您的原始帖子所建议的那样)
(open the browser console to see the output)
(打开浏览器控制台查看输出)
var userProfiles = [{ id:'1', name:'john' }, { id:'2', name:'mary' }];
var questions =[ { id:'1', text:'question john', createdBy:'1' }, { id:'2', text:'question mary', createdBy:'2' }];
var rows = _.map(userProfiles, function(user){
var question = _.find(questions, function(q){ return q.createdBy == user.id });
user.text = question? question.text:'';
return user;
})
_.each(rows, function(row){ console.log(row) });
the above answer assumes you are using id == createdBy as the joining column.
上面的答案假设您使用 id == createdBy 作为连接列。
回答by Ashok Damani
all u want is the ResultArray
calculated below:
你想要的只是ResultArray
下面的计算:
var userProfiles1= new Array(1, "ashok");
var userProfiles2= new Array(2, "amit");
var userProfiles3= new Array(3, "rajeev");
var UArray = new Array(userProfiles1, userProfiles2, userProfiles3);
var questions1= new Array(1, "text1", 2);
var questions2= new Array(2, "text2", 2);
var questions3= new Array(3, "text3", 1);
var questions4= new Array(4, "text4", 2);
var questions5= new Array(5, "text5", 3);
var questions6= new Array(6, "text6", 3);
var QArray = new Array(questions1, questions2, questions3, questions4, questions5, questions6);
var ResultArray = new Array();
for (var i=0; i<UArray.length; i++)
{
var uid = UArray[i][0];
var name = UArray[i][1];
for(var j=0; j<QArray.length; j++)
{
if(uid == QArray[j][2])
{
var qid = QArray[j][0]
var text = QArray[j][1];
ResultArray.push(qid +"," + text +","+ name)
}
}
}
for(var i=0; i<ResultArray.length; i++)
{
document.write(ResultArray[i] + "<br>")
}
demo : http://jsfiddle.net/VqmVv/
回答by basilikum
This is my attempt to make a somehow generic solution. I'm using Array.map
and the Array.index
methods here:
这是我尝试以某种方式制定通用解决方案。我正在使用Array.map
和Array.index
这里的方法:
var arr1 = [
{id: 1, text:"hello", oid:2},
{id: 2, text:"juhu", oid:3},
{id: 3, text:"wohoo", oid:4},
{id: 4, text:"yeehaw", oid:1}
];
var arr2 = [
{id: 1, name:"yoda"},
{id: 2, name:"herbert"},
{id: 3, name:"john"},
{id: 4, name:"walter"},
{id: 5, name:"clint"}
];
function merge(arr1, arr2, prop1, prop2) {
return arr1.map(function(item){
var p = item[prop1];
el = arr2.filter(function(item) {
return item[prop2] === p;
});
if (el.length === 0) {
return null;
}
var res = {};
for (var i in item) {
if (i !== prop1) {
res[i] = item[i];
}
}
for (var i in el[0]) {
if (i !== prop2) {
res[i] = el[0][i];
}
}
return res;
}).filter(function(el){
return el !== null;
});
}
var res = merge(arr1, arr2, "oid", "id");
console.log(res);
So basically you can define two arrays and one property for each array, so that prop1 will be replaced with all the properties of an item in array2 whose prop2 is equal to prop1.
所以基本上你可以为每个数组定义两个数组和一个属性,这样 prop1 将被替换为 array2 中 prop2 等于 prop1 的项目的所有属性。
The result in this case would be:
在这种情况下,结果将是:
var res = [
{id: 1, text:"hello", name:"herbert"},
{id: 2, text:"juhu", name:"john"},
{id: 3, text:"wohoo", name:"walter"},
{id: 4, text:"yeehaw", name:"yoda"}
];
Note that if there is more then one match, the first item will be used and if there is no match, the object will be removed from the resulting array.
请注意,如果有多个匹配项,将使用第一项,如果没有匹配项,则该对象将从结果数组中删除。
回答by georg
Just wanted to share some generic code:
只是想分享一些通用代码:
// Create a cartesian product of the arguments.
// product([1,2],['a','b'],['X']) => [[1,"a","X"],[1,"b","X"],[2,"a","X"],[2,"b","X"]]
// Accepts any number of arguments.
product = function() {
if(!arguments.length)
return [[]];
var p = product.apply(null, [].slice.call(arguments, 1));
return arguments[0].reduce(function(r, x) {
return p.reduce(function(r, y) {
return r.concat([[x].concat(y)]);
}, r);
}, []);
}
Your problem:
你的问题:
result = product(userProfiles, questions).filter(function(row) {
return row[0].id == row[1].createdBy;
}).map(function(row) {
return {
userName: row[0].name,
question: row[1].text
}
})
回答by 1983
You can do this using reduceand map.
First, create a mapping from IDs to names:
首先,创建从 ID 到名称的映射:
var id2name = userProfiles.reduce(function(id2name, profile){
id2name[profile.id] = profile.name;
return id2name;
}, {});
Second, create a new array of questions but with the name of the user who created the question in place of their ID:
其次,创建一个新的问题数组,但使用创建问题的用户名代替他们的 ID:
var qs = questions.map(function(q){
q.createdByName = id2name[q.createdBy];
delete q.createdBy;
return q;
});
回答by Shikiryu
I don't know any built-in function allowing to do so.
我不知道任何允许这样做的内置函数。
You can program your own function, something similar to this jsFiddle:
您可以编写自己的函数,类似于这个 jsFiddle:
var userProfiles = [{id:1, name:'name1'},{id:2,name:'name2'}];
var questions = [
{id:1, text:'text1', createdBy:'foo'},
{id:1, text:'text2', createdBy:'bar'},
{id:2, text:'text3', createdBy:'foo'}];
merged = mergeMyArrays(userProfiles,questions);
console.log(merged);
/**
* This will give you an array like this:
* [{id:1, name:name1, text:text1}, {...]
* params : 2 arrays to merge by id
*/
function mergeMyArrays(u,q){
var ret = [];
for(var i = 0, l = u.length; i < l; i++){
var curU = u[i];
for(var j = 0, m = q.length; j<m; j++){
if(q[j].id == curU.id){
ret.push({
id: curU.id,
name: curU.name,
text: q[j].text
});
}
}
}
return ret;
}
Or if you want a better "join" (SQL-y) :
或者,如果您想要更好的“加入”(SQL-y):
var userProfiles = [{id:1, name:'name1'},{id:2,name:'name2'}];
var questions = [
{id:1, text:'text1', createdBy:'foo'},
{id:1, text:'text2', createdBy:'bar'},
{id:2, text:'text3', createdBy:'foo'}];
merged = mergeMyArrays(userProfiles,questions);
console.log(merged);
/**
* This will give you an array like this:
* [{id:1, name:name1, questions:[{...}]]
* params : 2 arrays to merge by id
*/
function mergeMyArrays(u,q){
var ret = [];
for(var i = 0, l = u.length; i < l; i++){
var curU = u[i],
curId = curU.id,
tmpObj = {id:curId, name:curU.name, questions:[]};
for(var j = 0, m = q.length; j<m; j++){
if(q[j].id == curId){
tmpObj.questions.push({
text: q[j].text,
createdBy: q[j].createdBy
});
}
}
ret.push(tmpObj);
}
return ret;
}
Like in this jsFiddle
就像在这个 jsFiddle
回答by amaksr
This is easily done with StrelkiJS
这很容易用StrelkiJS完成
var userProfiles = new StrelkiJS.IndexedArray();
userProfiles.loadArray([
{id: 1, name: "Ashok"},
{id: 2, name: "Amit"},
{id: 3, name: "Rajeev"}
]);
var questions = new StrelkiJS.IndexedArray();
questions.loadArray([
{id: 1, text: "text1", createdBy: 2},
{id: 2, text: "text2", createdBy: 2},
{id: 3, text: "text3", createdBy: 1},
{id: 4, text: "text4", createdBy: 2},
{id: 5, text: "text5", createdBy: 3},
{id: 6, text: "text6", createdBy: 3}
]);
var res=questions.query([{
from_col: "createdBy",
to_table: userProfiles,
to_col: "id",
type: "outer"
}]);
The result will be:
结果将是:
[
[
{"id":1,"text":"text1","createdBy":2},
{"id":2,"name":"Amit"}
],
[
{"id":2,"text":"text2","createdBy":2},
{"id":2,"name":"Amit"}
],
[
{"id":3,"text":"text3","createdBy":1},
{"id":1,"name":"Ashok"}
],
[
{"id":4,"text":"text4","createdBy":2},
{"id":2,"name":"Amit"}
],
[
{"id":5,"text":"text5","createdBy":3},
{"id":3,"name":"Rajeev"}
],
[
{"id":6,"text":"text6","createdBy":3},
{"id":3,"name":"Rajeev"}
]
]