Reputation: 1477
I have the following code but I know that there must be a more efficient way to get to my end results. I need a comma separated string but when I try to use .toString I know that I'm not using it in the right place. I've included the code that I am currently using
function load_data() {
var response = [
{"email": "[email protected]","pmid": ["a22222", "a444444", "a555555", "a7777777", "a8888888"]},
{"email": "[email protected]", "pmid": ["b22222", "b444444", "b555555", "b7777777", "b8888888"]},
{"email": "[email protected]", "pmid": ["c22222", "c444444", "c555555", "c7777777", "c8888888"]},
{"email": "[email protected]", "pmid": ["d22222", "d444444", "d555555", "d7777777", "d8888888"]}
];
var singleEmail = $.grep(response, function (element, index) {
return element.email == '[email protected]';
});
var obj = singleEmail[0];
var pmid = obj.pmid;
var pmidList = ''
for (var i = 0; i < pmid.length; i++) {
pmidList += pmid[i] + ',';
}
alert(pmidList);
}
Also is using grep any more efficient than just looping?
Thanks
Upvotes: 0
Views: 235
Reputation: 53821
Using jQuery is never more efficient. JS has many useful methods these days. Check MDN for browser support though.
Find the right element:
// modern
const element = response.find((el) => el.email == '[email protected]');
// compatible
var element = response.find(function(el) {
return el.email == '[email protected]';
});
Stringify the array:
const pmidList = element.pmid.join(',');
// or var for compatibility
pmidList
won't have a trailing ,
like your code, but I'm guessing that's good.
References & support:
const
vs var
array.find
vs array.filter
(grep)Upvotes: 3