我已经看到很多与js对象排序有关的其他问题,其中大多数都倾向于建议使用.map方法根据属性的值对对象或对象数组进行排序,但我&#39 ;我试图实现略微不同的东西。
我试图改变这种对象格式:
{
"commits": [
{
"repository": "example-repo-1",
"commit_hash": "example-hash-1"
},
{
"repository": "example-repo-1",
"commit_hash": "example-hash-1.2"
},
{
"repository": "example-repo-2",
"commit_hash": "example-hash-2"
}
]
}
进入使用' repository'的值格式化的对象像这样:
{
"example-repo-1": [
{
"repository": "example-repo-1",
"commit_hash": "example-hash-1"
},
{
"repository": "example-repo-1",
"commit_hash": "example-hash-1.2"
}
],
"example-repo-2": [
{
"repository": "example-repo-2",
"commit_hash": "example-hash-2"
}
]
}
所以我需要获取我的原始对象,它是一个带有其他对象数组的对象,以返回一个包含大量数组的对象,这些数组以repository属性的值命名并包含与该属性值匹配的每个对象。
答案 0 :(得分:2)
使用 Array#forEach
方法
var data = {
"commits": [{
"repository": "example-repo-1",
"commit_hash": "example-hash-1"
}, {
"repository": "example-repo-1",
"commit_hash": "example-hash-1.2"
}, {
"repository": "example-repo-2",
"commit_hash": "example-hash-2"
}]
};
var res = {};
data.commits.forEach(function(v) {
// define the pproperty if already not defined
res[v.repository] = res[v.repository] || [];
// push the reference to the object or recreate depense on your need
res[v.repository].push(v);
})
console.log(res);
或使用 Array#reduce
方法
var data = {
"commits": [{
"repository": "example-repo-1",
"commit_hash": "example-hash-1"
}, {
"repository": "example-repo-1",
"commit_hash": "example-hash-1.2"
}, {
"repository": "example-repo-2",
"commit_hash": "example-hash-2"
}]
};
var res = data.commits.reduce(function(obj, v) {
// define property if not defined
obj[v.repository] = obj[v.repository] || [];
// push the object
obj[v.repository].push(v);
// return the result object
return obj;
}, {})
console.log(res);
答案 1 :(得分:-1)
尝试这样的事情
var input = {
"commits": [
{
"repository": "example-repo-1",
"commit_hash": "example-hash-1"
},
{
"repository": "example-repo-1",
"commit_hash": "example-hash-1.2"
},
{
"repository": "example-repo-2",
"commit_hash": "example-hash-2"
}
]
};
var output = {};
input.commits.forEach(function(el){
if(!output[el.repository])
output[el.repository] = [];
output[el.repository].push[el];
})
console.log(output);