Reputation: 638
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:
replace all "Business Type"
to "businessTypeId"
[delete square brackets]
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
Upvotes: 0
Views: 41
Reputation: 4337
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)
Upvotes: 1
Reputation: 14788
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);
Upvotes: 2