gpt4 book ai didi

javascript - 根据字段划分 JSON 对象数组

转载 作者:行者123 更新时间:2023-12-03 07:42:54 25 4
gpt4 key购买 nike

示例 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 数组拆分为多个数组。我的意思是一个 JSON 数组包含地址为“印度”的员工,另一个包含下一个地址,依此类推。

最佳答案

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

关于javascript - 根据字段划分 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35331818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com