underscore.js如何组合2个集合

时间:2014-01-28 13:16:40

标签: javascript backbone.js underscore.js

我有两个集合A和B.(A,B具有完全相同的结构,但节点值不同)

现在我想将A添加到B中,完全按顺序:A B并且没有合并或更改任何 他们内部的节点。 (就像联合行动一样){A} + {B}

我已经阅读了下划线的文档,但找不到能够完成这项工作的正确功能。

任何想法?

==========使用示例进行更新========样本从较大的结构中简化,如果有错误请告诉我========= < / p>

var collection1 = [{
"date": "29 January 2014",
"items": [{
    "name": "Jack",
    "score": 90,
    "title": "programmer"
}, {
    "name": "TOM",
    "score": 52,
    "title": "designer"
}]
}, {
"date": "28 January 2014",
"items": [{
    "name": "Jim",
    "score": 30,
    "title": "driver"
}, {
    "name": "William",
    "score": 52,
    "title": "worker"
  }]
}]



var collect2 = [{
"date": "26 January 2014",
"items": [{
    "name": "Marry",
    "score": 92,
    "title": "teacher"
}, {
    "name": "TOM",
    "score": 52,
    "title": "designer"
}]

}]

========预期输出==============

[{
"date": "29 January 2014",
"items": [{
    "name": "Jack",
    "score": 90,
    "title": "programmer"
}, {
    "name": "TOM",
    "score": 52,
    "title": "designer"
}]
}, {
"date": "28 January 2014",
"items": [{
    "name": "Jim",
    "score": 30,
    "title": "driver"
}, {
    "name": "William",
    "score": 52,
    "title": "worker"
}]

}, {

"date": "26 January 2014",
"items": [{
    "name": "Marry",
    "score": 92,
    "title": "teacher"
}, {
    "name": "TOM",
    "score": 52,
    "title": "designer"
}]


}]

2 个答案:

答案 0 :(得分:3)

我认为您所寻找的只是Array.concat

var foo = ['a','b','c'];
var bar = ['d','e','f'];

var all = foo.concat(bar); // ['a','b','c','d','e','f'];

答案 1 :(得分:1)

使用Underscore#extend作为:_.extend(collection1, collection2);

<强>样本

col1 = { aa: 'aa', cc: 'cc' }; col2 = { bb: 'bb', dd: 'dd' };
_.extend(col1, col2)
console.log(col1);
# Prints Object {aa: "aa", cc: "cc", bb: "bb", dd: "dd"}