简体   繁体   中英

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"

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"

  2. [delete square brackets]

  3. add "" to id (id is the number in Business Type)

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

You could use the array 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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