我想迭代array loop
并根据array
中对象的属性名称和值来执行操作。
从一个非常“扁平”的array
文件中检索JSON
,该文件是来自多个git
存储库的git
提交日志的集合(解析为{{1}从JSON
到this project)。
我想做的一些事情是:
但我最感兴趣的是如何选择/分组/过滤所有共享特定属性值的提交(例如 repository 或 author_email 或者 date_day_week )而没有指定任何显式值?
我已手动完成(请参阅下面代码块中从下到上的第7行):
bash
但我想做的是分组/过滤所有共享给定属性值的提交(即存储库 lemon , apple , orange 等)动态地结合在一起。一旦我知道如何做到这一点,我希望能够对可能共享属性值的其他属性名称执行相同操作,例如 author_email , date_day_week , date_month_name ,插入等
以下是原始// == request and parse JSON data == //
// define data source
var data_source = "src/json/data.json";
// request the data
var xhr = new XMLHttpRequest();
xhr.open("GET", data_source);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) { return; }
if ((this.status >= 200 && this.status < 300) || this.status === 0) {
// get raw data
data_JSON = this.responseText;
// parse JSON data to JavaScript format
data_parsed = JSON.parse(data_JSON);
// manipulate data 'outside' the xhr request to keep things tidy
manipulateData(data_parsed);
} else {
console.log('There was an error completing the XMLHttpRequest...');
}
};
xhr.send();
// create a callback function to do stuff 'outside' xhr
function manipulateData(object){
// define root object
var commit = object.commits;
// loop through every item so that we can iterate with them
for (var i = 0; i < commit.length; i++){
// define 'commit[i]' as 'item' so that code is more legible
var item = commit[i];
// list property names and their values on console
for (var key in item) {
if (item.hasOwnProperty(key)) {
// list only items under 'lemon' repository <-- this is where I need it to be generic so I can group/filter all items under a common repository and do things with it
if (item.repository == 'lemon') {
console.log(key + " -> " + item[key]);
}
}
}
}
}
文件,在data.json
声明为变量:
var data_source = "src/json/data.json";
感谢任何帮助!
答案 0 :(得分:5)
试试这个:
function groupBy(data,key, val){
var arr=[];
for(var i in data){
if(data[i][key]==val) arr.push(data[i])
}
return arr;
}
console.log(groupBy(object.commits,"repository","lemon"))
对于分组而未指定val
:
function groupByAuto(data, key){
var groups={};
for(var i in data){
if(!groups.hasOwnProperty(data[i][key])) groups[data[i][key]]=[];
groups[data[i][key]].push(data[i]);
}
return groups;
}
console.log(groupByAuto(data.commits, "repository"))