create string from JSON values in jQuery

强颜欢笑 提交于 2019-12-24 09:58:41

问题


I'd like to create a string of ISBNs from a JSON object to search multiple books in Google Books.

I can get the ISBNs by parsing Google Books' JSON with this path:

volumeInfo.industryIdentifiers[0].identifier

(Here I'm doing that to get a simple book list: jsfiddle.net/LyNfX )

How do I string together each value in order to get this query structure, where each ISBN is preceded by "isbn:", and after the first one they are separated by "OR"

https://www.google.com/search?btnG=Search+Books&tbm=bks&q=Springfield+isbn:1416549838+OR+isbn:068482535X+OR+isbn:0805093079+OR+isbn:0306810328

回答1:


Starting from an array of ISBN strings called list:

list.map(function(v){return "isbn:"+v;}).join("+OR+")

As for building your list of ISBN's which I understand to be the identifier prop in your industryIdentifiers (if industryIdentifier is a bona fide Array):

var list = [];
volumeInfo.industryIdentifiers.forEach(function(e,i){list.push(e.identifier);});

You could also just build the final string in one fell swoop and not build an array at all, but this means extra logic to prevent inserting an extra delimiter (+OR+ being the delimiter)

var output = "";
volumeInfo.industryIdentifiers.forEach(function(e,i){output += "isbn:"+e.identifier+"+OR+";});
output.slice(0,-4); // clear out last +OR+



回答2:


var arrayOfISBNs = [123,456,789...];
var result = "isbn:" + arrayOfISBNs.join(" OR isbn:")

Just use array join.



来源:https://stackoverflow.com/questions/14689817/create-string-from-json-values-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!