2015-05-27 63 views
0

我的第一個字母要組JSON數組組JSON對象在JavaScript

這是我的數據記錄從sqlitedb quesry

例:

[ 
    {"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 
    }] 
} 

回答

0

試試這個

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);