我有以下代码,但我知道必须有一种更有效的方法来获得最终结果。我需要一个逗号分隔的字符串,但是当我尝试使用 .toString 时,我知道我没有在正确的位置使用它。我已经包含了我当前正在使用的代码
function load_data() {
var response = [
{"email": "a@123.com","pmid": ["a22222", "a444444", "a555555", "a7777777", "a8888888"]},
{"email": "b@123.com", "pmid": ["b22222", "b444444", "b555555", "b7777777", "b8888888"]},
{"email": "c@123.com", "pmid": ["c22222", "c444444", "c555555", "c7777777", "c8888888"]},
{"email": "d@123.com", "pmid": ["d22222", "d444444", "d555555", "d7777777", "d8888888"]}
];
var singleEmail = $.grep(response, function (element, index) {
return element.email == 'a@123.com';
});
var obj = singleEmail[0];
var pmid = obj.pmid;
var pmidList = ''
for (var i = 0; i < pmid.length; i++) {
pmidList += pmid[i] + ',';
}
alert(pmidList);
}
使用 grep 是否比仅仅循环更有效?
谢谢
最佳答案
使用 jQuery 从未如此高效。如今,JS 有许多有用的方法。请检查 MDN 的浏览器支持。
找到正确的元素:
// modern
const element = response.find((el) => el.email == 'a@123.com');
// compatible
var element = response.find(function(el) {
return el.email == 'a@123.com';
});
字符串化数组:
const pmidList = element.pmid.join(',');
// or var for compatibility
pmidList
不会像您的代码那样有尾随 ,
,但我猜这很好。
引用与支持:
关于javascript - 过滤 json 对象并循环结果 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438173/