我试图从不同的集合中获取一些数据并将它们作为一个对象数组返回,但我需要合并具有相同标题的对象。
'search': function(value) {
const res1 = Col1.find({ title: new RegExp(value, 'i') }, { fields: { title: 1, type: 1 } }).fetch() || [],
res2 = Col2.find({ title: new RegExp(value, 'i') }, { fields: { title: 1, type: 1 } }).fetch() || []
let result = res1.concat(res2)
return result
}
假设第一个集合将为我提供 type
字段的“汽车”,第二个集合将给我“动物”。
如果有相同的标题,我需要更改 type
字段并添加一些内容。
{ _id: 1, title: 'mercedes', type: 'cars' }
{ _id: 2, title: 'monkey', type: 'animals' }
{ _id: 3, title: 'jaguar', type: 'cars' }
{ _id: 4, title: 'jaguar', type: 'animals' }
应该转化为
{ _id: 1, title: 'mercedes', type: 'cars' }
{ _id: 2, title: 'monkey', type: 'animals' }
{ title: 'jaguar', type: 'multiple', results: [
{ _id: 3, title: 'jaguar', type: 'cars' }
{ _id: 4, title: 'jaguar', type: 'animals' }
] }
最佳答案
您可以对相同的标题使用哈希表 titles
并将项目分配给数组并保存索引。
var data = [{ _id: 1, title: 'mercedes', type: 'cars' }, { _id: 2, title: 'monkey', type: 'animals' }, { _id: 3, title: 'jaguar', type: 'cars' }, { _id: 4, title: 'jaguar', type: 'animals' }],
result = data.reduce(function (titles) {
return function (r, a) {
if (titles[a.title]) {
if (titles[a.title].results.length === 1) {
r[titles[a.title].index] = { title: a.title, type: 'multiple', results: titles[a.title].results };
}
titles[a.title].results.push(a);
} else {
titles[a.title] = { index: r.push(a) - 1, results: [a] };
}
return r;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以将哈希表移到闭包之外。
var data = [{ _id: 1, title: 'mercedes', type: 'cars' }, { _id: 2, title: 'monkey', type: 'animals' }, { _id: 3, title: 'jaguar', type: 'cars' }, { _id: 4, title: 'jaguar', type: 'animals' }],
titles = Object.create(null),
result = data.reduce(function (r, a) {
if (titles[a.title]) {
if (titles[a.title].results.length === 1) {
r[titles[a.title].index] = { title: a.title, type: 'multiple', results: titles[a.title].results };
}
titles[a.title].results.push(a);
} else {
titles[a.title] = { index: r.push(a) - 1, results: [a] };
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - JS : Merge objects with identical title value into new array object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44231080/