简体   繁体   中英

javascript map and join on an array

d = [
    ["a", "Adobe"]
    ["b", "Boston"]
    ["c", "Cars"]
    ["d", "Dominos"]
    ["e", "Microsoft"]
]
const asString = d.map(function(x){
        x[0],'=',x[1]
    }).join('&');
  console.log(asString);

I'm trying to generate a query string from the above array, but seem to be getting only &&&& . The original solution used Template Literals and was like this:

const asString = d
      .map(x => `${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`)
      .join('&');
  console.log(asString);

This works fine, but I don't want to use Template Literals.

The end result is a querystring like this: a=Adobe&b=Boston&c=Cars&d=Dominos&e=Microsoft

Just using map and join:

 const d = [ ["a", "Adobe"], ["b", "Boston"], ["c", "Cars"], ["d", "Dominos"], ["e", "Microsoft"] ] let queryString = d.map(x=>x.map(encodeURIComponent).join("=")).join("&") console.log(queryString) // Without arrow function queryString = d.map(function(x){ return x.map(encodeURIComponent).join("=") }).join("&"); console.log(queryString)

You could take the key and value and return the new strings.

 const d = [["a", "Adobe Photoshop"], ["b", "Boston"], ["c", "Cars"], ["d", "Dominos"], ["e", "Microsoft"]], asString = d.map(([key, value]) => key + '=' + encodeURIComponent(value)).join('&'); console.log(asString);

You're not returning any values from your map callback:

d.map(function(x){
        x[0],'=',x[1]
    }).join('&');

should be:

d.map(function(x){
        return x[0] + '=' + x[1]
    }).join('&');

"Classic" style functions don't return values in the same way as lambda (arrow) functions do, so you need to explicitly return the value.

Using reduce

 d = [ ["a", "Adobe"], ["b", "Boston"], ["c", "Cars"], ["d", "Dominos"], ["e", "Microsoft"] ] let join = d.reduce((acc, elem)=>{ return acc + elem.join("=") + '&' },""); console.log(join.slice(0, -1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM