2016-02-11 121 views
0

樣品JSON:鴻溝JSON陣列

"employees":[ 
    {"firstName":"John", "lastName":"Doe", "address ": "India "}, 
    {"firstName":"Anna", "lastName":"Smith", "address ": "Europe "}, 
    {"firstName":"Peter","lastName":"Jones", "address ": " Canada "}, 
    {"firstName":"hem", "lastName":"fik", "address ": " Europe "}, 
    {"firstName":"kin", "lastName":"ress", "address ": " India "}, 
    {"firstName":"jack","lastName":"pink", "address ": "Canada "} 
] 

我想要分割上述JSON數組成根據針對多個陣列field.I意味着一個JSON陣列包含具有員工地址是「印度「,另一個有下一個等等。

+0

所以,呃,解析JSON,然後通過所產生的陣列將每個人擁有的國家鑰匙(你根據需要添加你循環)的新對象循環。你卡在哪裏? – nnnnnn

回答

1

使用Array.prototype.filter()函數用於根據情況過濾出數組元素。

var employees = [{ 
 
    "firstName": "John", 
 
    "lastName": "Doe", 
 
    "address ": "India " 
 
}, { 
 
    "firstName": "Anna", 
 
    "lastName": "Smith", 
 
    "address ": "Europe " 
 
}, { 
 
    "firstName": "Peter", 
 
    "lastName": "Jones", 
 
    "address ": " Canada " 
 
}, { 
 
    "firstName": "hem", 
 
    "lastName": "fik", 
 
    "address ": " Europe " 
 
}, { 
 
    "firstName": "kin", 
 
    "lastName": "ress", 
 
    "address ": " India " 
 
}, { 
 
    "firstName": "jack", 
 
    "lastName": "pink", 
 
    "address ": "Canada " 
 
}]; 
 
var address = employees.map(function(val) { 
 
    return val['address '].trim(); 
 
}) 
 
var arrays = {}; 
 
for (i in address) { 
 
    arrays[address[i]] = employees.filter(function(val) { 
 
    return val['address '].toLowerCase().indexOf(address[i].toLowerCase()) != -1; 
 
    }); 
 
} 
 
console.log(arrays);

+0

地址不是靜態的...這個JSON是動態的 –

+0

@SmitaAhinave地址將是一個單一的措辭國名或它將包含更多? –

+0

@SmitaAhinave我更新了答案。 – RRK