【问题标题】:How to replace all substrings with other string javascript如何用其他字符串javascript替换所有子字符串
【发布时间】:2021-02-10 22:14:43
【问题描述】:

我正在加载数据,然后将其放入输入中,它输入的数据位于名称“业务类型”下,我需要将其更改为“业务类型 ID”

例如

其实我有

[{"URL":"http://www.restaurant.com","Business Type":1},{"URL":"http://www.hotel.com","Business Type":2}]

我想:

  1. 将所有"Business Type" 替换为"businessTypeId"

  2. [delete square brackets]

  3. ""添加到id(id是业务类型中的数字)

这是预期的结果

{"url":"http://www.restaurant.com","businessTypeId":"1"},{"url":"http://www.hotel.com","businessTypeId":"2"}

这是我的代码

placesArray.push(JSON.stringify(results.data));
console.log(placesArray);
document.getElementById('places').value = placesArray;

placesArray 包含我要更改的字符串

【问题讨论】:

  • 您对placesArray.push(JSON.stringify(results.data)); 有什么期望,console.log(placesArray); 之后会记录什么?由于它是一个字符串数组,它根本不可能是显示为“实际上我有”的内容。
  • 该控制台日志仅用于测试,忽略它

标签: javascript arrays string


【解决方案1】:

你可以使用数组map函数:

const data = [
  { "URL":"http://www.restaurant.com", "Business Type": 1},
  { "URL":"http://www.hotel.com", "Business Type": 2 },
];

const result = data.map(value => ({
  url: value.URL,
  businessTypeId: value["Business Type"]?.toString(),
}));

console.log(result);

【讨论】:

  • 我得到 Uncaught TypeError: Cannot read property 'toString' of undefined
  • 如果数组值之一中缺少 Business Type 字段,则会发生这种情况。我将更新我的答案以说明缺少的字段。
  • 谢谢,这行得通,但是当我尝试将字符串更改为我的 placesArray 时,我得到一个 [object Object] 结果,如果我使用 JSON.stringify(result) 我只得到这个 [{} ]
【解决方案2】:

const data=
[{"URL":"http://www.restaurant.com","Business Type":1},{"URL":"http://www.hotel.com","Business Type":2}]

//"Buisness Type" is a key, so firstly, go through each index, then in each index search through its keys and do replacing stuffs
data.forEach(a=>{
  Object.keys(a).forEach(b=>{
    if(b=="Business Type"){//what you want replaced
      var n=a[b].toString() //value to put in replaced key(and to string because you told me that you want string data not number data)
      delete(a[b]) //deleting old key
      a["businessTypeId"]=n //adding replaced key with previous value
    }
  })
})

console.log(data)

【讨论】:

  • 谢谢!但我得到一个带有[方括号]的结果,我必须删除那个[],你的代码我必须使用 JSON.stringify(data);因为结果是 [object][object]。我怎样才能删除那个[]?我必须将“”添加到身份证号码。例如 "businessTypeId":"1"
  • @AndréCuellarAvaroma 首先是..尝试将数据放入 HTML 元素会做类似的事情..其次,对于将 1 转换为 "1" 考虑完成
  • 当我将结果放入输入时,将其放在括号中
  • 我解决了添加这个 .toString().replace(/^[([\s\S]*)]$/,'$1')
猜你喜欢
  • 1970-01-01
  • 2021-12-14
  • 2019-11-21
  • 2022-01-11
  • 2023-03-19
  • 2017-01-02
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多