使用 reduce fnt 而不是 map

Using reduce fnt instead of map

本文关键字:map reduce fnt 使用      更新时间:2023-09-26

关于如何使用reduce重构函数的任何建议,因为我不应该在这里使用map

试试这个:

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('&');
}

或者没有模板字符串:

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('&');
}

在这里使用 map 而不是 reduce 是合适的,您只应该映射到可以在join ing 之前concat的数组数组。

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("&");
}

由于您使用 Ramda 标记了此内容,因此您可以使用concat撰写map或立即使用chain