Underscore JS 嵌套每个合并对象
Underscore JS nested each merge objects
我有两个要合并的对象数组
var status = [
{name: 'status_1', pk:1 }, {name: 'status_2', pk:2 }
]
var to_be_merged = [
{'status_pk': 1, 'value': 10}, {'status_pk': 2, value: 20}
]
想要的结果
var status = [
{name:'status_1',
pk:1,
to_be_merged:{
'status_pk': 1, 'value': 10
}, {
name: 'status_2',
pk:2,
to_be_merged: {
'status_pk': 2, value: 20}
},
]
我试过使用嵌套 _.each
但我失去了上面的范围 each
_.each(status, function(status) {
var objs = _.each(to_be_merged, function(x) {
if (x.status_pk == status.pk) {
// do something
}
})
})
map
应该能帮到你。将它与 merge
和 where
合并,将两项合并在一起。
_.each(status, function(item) {
item['to_be_merged'] = _.find(to_be_merged, function(other) {
return other['status_pk'] === item.pk;
});
})
这有点冗长,但您可以看到发生了什么:
var stat = {
s: [
{name: 'status_1', pk:1 }, {name: 'status_2', pk:2 }
],
m: [
{'status_pk': 1, 'value': 10}, {'status_pk': 2, value: 20}
]}
var merged = []
_(stat.s).each(function(s){
_(stat.m).each(function(m){
var obj = {};
if(s.pk == m.status_pk){
obj.name = s.name;
obj.pk = s.pk;
obj.to_be_meged = m
merged.push(obj);
}
})
})
console.log(merged);
我有两个要合并的对象数组
var status = [
{name: 'status_1', pk:1 }, {name: 'status_2', pk:2 }
]
var to_be_merged = [
{'status_pk': 1, 'value': 10}, {'status_pk': 2, value: 20}
]
想要的结果
var status = [
{name:'status_1',
pk:1,
to_be_merged:{
'status_pk': 1, 'value': 10
}, {
name: 'status_2',
pk:2,
to_be_merged: {
'status_pk': 2, value: 20}
},
]
我试过使用嵌套 _.each
但我失去了上面的范围 each
_.each(status, function(status) {
var objs = _.each(to_be_merged, function(x) {
if (x.status_pk == status.pk) {
// do something
}
})
})
map
应该能帮到你。将它与 merge
和 where
合并,将两项合并在一起。
_.each(status, function(item) {
item['to_be_merged'] = _.find(to_be_merged, function(other) {
return other['status_pk'] === item.pk;
});
})
这有点冗长,但您可以看到发生了什么:
var stat = {
s: [
{name: 'status_1', pk:1 }, {name: 'status_2', pk:2 }
],
m: [
{'status_pk': 1, 'value': 10}, {'status_pk': 2, value: 20}
]}
var merged = []
_(stat.s).each(function(s){
_(stat.m).each(function(m){
var obj = {};
if(s.pk == m.status_pk){
obj.name = s.name;
obj.pk = s.pk;
obj.to_be_meged = m
merged.push(obj);
}
})
})
console.log(merged);