简体   繁体   English

如何用其他字符串 javascript 替换所有子字符串

[英]How to replace all substrings with other string javascript

I am loading data and then putting it in an input, the data that it enters goes under the name "Business Type" and I need to change that to "businessTypeId"我正在加载数据,然后将其放入输入中,它输入的数据名为“业务类型”,我需要将其更改为“businessTypeId”

for example例如

actually I have其实我有

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

I would like to:我想:

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

  2. [delete square brackets]

  3. add "" to id (id is the number in Business Type) id 加"" (id 是业务类型中的数字)

this is the espected result这是预期的结果

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

this is my code这是我的代码

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

placesArray contains the string that I would like to change placesArray包含我想更改的字符串

You could use the array map function:您可以使用数组map function:

 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);

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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