在 javascript 中分组 json 个对象
Group json object in javascript
我想按第一个字母
对 json 数组进行分组
这是我从sqlitedb查询的数据记录
例如:
[
{"pid":2,"ID":1,"title":"aasas as"},
{"pid":3,"ID":2,"title":"family"},
{"pid":4,"ID":3,"title":"fat111"}
]
我需要这个输出
{
A: [{
title: "aasas as",
ID: 1
}],
F: [{
title: "family",
ID: 2
}, {
title: "fat111",
ID: 3
}]
}
试试这个
var data = [
{"pid":2,"ID":1,"title":"aasas as"},
{"pid":3,"ID":2,"title":"family"},
{"pid":4,"ID":3,"title":"fat111"}
];
var result = {},
i,
len = data.length,
key;
for (i = 0; i < len; i++) {
key = data[i].title.substring(0, 1); // get first word from string
if (!result[key]) { // if key does not exists in result, create it
result[key] = [];
}
result[key].push(data[i]); // else push data
}
console.log(result);
我想按第一个字母
对 json 数组进行分组这是我从sqlitedb查询的数据记录
例如:
[
{"pid":2,"ID":1,"title":"aasas as"},
{"pid":3,"ID":2,"title":"family"},
{"pid":4,"ID":3,"title":"fat111"}
]
我需要这个输出
{
A: [{
title: "aasas as",
ID: 1
}],
F: [{
title: "family",
ID: 2
}, {
title: "fat111",
ID: 3
}]
}
试试这个
var data = [
{"pid":2,"ID":1,"title":"aasas as"},
{"pid":3,"ID":2,"title":"family"},
{"pid":4,"ID":3,"title":"fat111"}
];
var result = {},
i,
len = data.length,
key;
for (i = 0; i < len; i++) {
key = data[i].title.substring(0, 1); // get first word from string
if (!result[key]) { // if key does not exists in result, create it
result[key] = [];
}
result[key].push(data[i]); // else push data
}
console.log(result);