sisimh February 2016

Using reduce fnt instead of map

Any advise on how can I refactor my function using reduce, as I should not use map here?

Answers


Radosław M February 2016

Try this:

function serializeParams (object) {
    return Object.keys(object)
        .reduce((query, key) =>
            Array.isArray(object[key])
                ? query.concat(object[key].map(value => `${key}=${encodeURIComponent(value)}`))
                : query.concat(`${key}=${encodeURIComponent(object[key])}`)
        , [])
        .join('&');
}

Or without template strings:

function serializeParams (object) {
    return Object.keys(object)
        .reduce((query, key) =>
            Array.isArray(object[key])
                ? query.concat(object[key].map(value => key + '=' + encodeURIComponent(value)))
                : query.concat(key + '=' + encodeURIComponent(object[key]))
        , [])
        .join('&');
}


Bergi February 2016

Using map instead of reduce is appropriate here, you only should map to an array of arrays that you can concat before joining.

function serializeParams(obj) {
  return Array.protoype.concat.apply([], keys(obj).map(key => {
    let value = obj[key];
    return Array.isArray(value)
      ? value.map(v => key +"=" + encodeURIComponent(v))
      : [key + "=" + encodeURIComponent(value)];   
  })).join("&");
}

Since you tagged this with Ramda, you can either compose map with concat or use chain right away.

Post Status

Asked in February 2016
Viewed 2,626 times
Voted 12
Answered 2 times

Search




Leave an answer