我有一个包含这样对象的数组:
[{recordID:'123'},{recordID:'123-opp'},{recordsID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'},...]
所以有一些具有相同recordID的对象只添加了一个-opp
,有些是单个的,没有-opp
我想要做的是组合数组中的相应对象。而另一个单独在一个数组中。例如:
[[{recordID:'123'},{recordID:'123-opp'}], [{recordID:'456'},{recordID:'456-opp'}],[{recordID:'789'}],[{recordID:'980'}],...]
提及:有时最后可能是-opp
,有时候-ref
。
我尝试了多种方法,但没有得到正确的结果。这是我的代码:
.then(function(dbResult){ //sort and filter the corresponding records
var records = [];
var indexToDelete;
dbResult.forEach(function(item, index){
var recordPair = dbResult.filter(function(element, i){
if(element.recordId.includes(item.recordId)){
indexToDelete = i;
return true;
}else{
return false;
}
})
records.splice(indexToDelete,1);
records.push(recordPair);
})
console.log(records)
return records;
})
也许有人有更好的解决方案。
答案 0 :(得分:1)
您可以通过以下方式执行此操作
let arr = [{recordID:'123'},{recordID:'123-opp'},{recordID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'}];
let cleanVariable = (str) => +str.replace(/\-opp|\-ref/,'');
let matchVariable = (str1, str2) => cleanVariable(str1) == cleanVariable(str2);
let result = arr.sort((a, b) => cleanVariable(a.recordID) - cleanVariable(b.recordID)).reduce((a, b) => {
if(a.length == 0) a.push([]);
if(a[a.length-1].length == 0) a[a.length-1].push(b);
else if(matchVariable(a[a.length-1][a[a.length-1].length-1].recordID, b.recordID)) a[a.length-1].push(b);
else a.push([b]);
return a;
}, []);
console.log(result);

答案 1 :(得分:1)
您可以通过将id的一部分与相同组的哈希表一起使用来对结果进行分组。
var array = [{ recordID: '123' }, { recordID: '123-opp' }, { recordID: '456' }, { recordID: '456-opp' }, { recordID: '789' }, { recordID: '980' }],
hash = Object.create(null),
result = [];
array.forEach(function (o) {
var key = o.recordID.match(/^\d+/);
if (!hash[key]) {
hash[key] = [];
result.push(hash[key]);
}
hash[key].push(o);
});
console.log(result);
console.log(hash);

.as-console-wrapper { max-height: 100% !important; top: 0; }