我有一个包含这样对象的数组:
[{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;
})
也许有人有更好的解决方案。
最佳答案
您可以通过将 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; }
关于javascript - 组数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259303/