连接.map()值

时间:2018-08-22 01:24:41

标签: javascript

我已经使用.map()从表单值对象创建查询参数。

handleClick(e) {

  const { monthOffset, yearOffset } = this.state

  // call setState once
  this.setState({ 

    // Always decrement month offset
    monthOffset : monthOffset - 1, 

    // Only decrement year offset if current month offset === 12
    yearOffset : (monthOffset === 12) ? yearOffset - 1 : yearOffset

  }, () => {

    console.log("state updated to", this.state)
  })

  console.log("clicked")
}

现在我已经操纵了每个对象和键,我想将它们全部连接在一起以创建一个查询字符串。

我该怎么做?

2 个答案:

答案 0 :(得分:8)

您的.map现在实际上并未映射任何内容-只是console.log生成并返回undefined

如果要查询字符串,则只应在 first 前添加?,并在所有参数之间使用&。因此,您可以join之前&,然后在开头添加?

您还可以考虑使用Object.entries一次获取键和值,而不必引用object[key]

您还应该使用encodeURIComponent将对URL不安全的字符(如普通空格)转换为适当的转义序列(如%20):

const object = {
  "selectedPriority": "9",
  "selectedShipOption": "Private Label",
  "selectedCustomerStatus": "No",
  "selectedColdOptions": [],
  "selectedDistributionOptions": ["Retail"],
  "selectedPackagingOption": "Lid",
  "selectedPrepOption": "Hot Water",
  "productParams": ["Kosher\n"],
  "productAppearance": "Grill Marks",
  "storage": "CAP",
  "preservatives": "Only natural preservatives"
}

const result = '?' + Object.entries(object).map(([key, value]) => {
  return `${key}=${encodeURIComponent(value)}`
}).join('&');
console.log(result);

不需要创建中间数组的另一种方法是使用reduce,并传递?的初始值:

const object = {
  "selectedPriority": "9",
  "selectedShipOption": "Private Label",
  "selectedCustomerStatus": "No",
  "selectedColdOptions": [],
  "selectedDistributionOptions": ["Retail"],
  "selectedPackagingOption": "Lid",
  "selectedPrepOption": "Hot Water",
  "productParams": ["Kosher\n"],
  "productAppearance": "Grill Marks",
  "storage": "CAP",
  "preservatives": "Only natural preservatives"
};

const result = Object.entries(object).reduce((a, [key, value], i) => (
  a + (i !== 0 ? '&' : '' ) + `${key}=${encodeURIComponent(value)}`
), '?');
console.log(result);

答案 1 :(得分:1)

您可以通过应用join function来串联它们。

const object = {
  "selectedPriority": "9",
  "selectedShipOption": "Private Label",
  "selectedCustomerStatus": "No",
  "selectedColdOptions": [],
  "selectedDistributionOptions": ["Retail"],
  "selectedPackagingOption": "Lid",
  "selectedPrepOption": "Hot Water",
  "productParams": ["Kosher\n"],
  "productAppearance": "Grill Marks",
  "storage": "CAP",
  "preservatives": "Only natural preservatives"
};

const result = Object.keys(object)
  .map((key, index) => `?${key}=${object[key]}`)
  .join('\n');

console.log(result);

如果要创建URL查询字符串,请不要重复?并通过将encodeURIComponent应用于每个值来对值进行编码,然后与&联接。