'Convert key value object to json - javascript

Hey All I have this object that I try to convert to json. I tried

reportDropDownsJson2 =  JSON.parse('{"' + reportDropDownsJson.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) });
            reportDropDownsJson['downloadcsv'] = true; 

and the result is:

TypeError: reportDropDownsJson.replace is not a function

this is the object (called reportDropDownsJson) that I try to convert to json

ad_type: ""
agency_id[]: ""
auction_type: ""
brand_id[]: ""
campaign: ""
campaign-drop: ""
column_filter[]: (23) ['Timestamp', 'Date', 'Hour', 'Brand', 'Requests', 'Bids', 'Bid %', 'Wins', 'Win %', 'Fill %', 'Imps Pixel', 'Revenue $', 'Cost $', 'eCPM', 'Sales Person', 'AdOPS Person', 'Account Manager Person', 'IVT Provider 1', 'Viewability Provider 1', 'VCR', 'CTR', 'VTR', 'Campaign']
deal_id[]: ""
deal_personnel[]: ""
deal_type[]: ""
device_type: ""
dsp_id[]: ""
edit_saved_report: ""
end_date: "2022-02-16"
frozen_filter[]: "Timestamp"
group_by[]: ""
interval: "hourly"
media_type: ""
office_country[]: "All"
pub_id[]: ""
ssp_id[]: ""
start_date: "2022-02-16"
timezone: "US/Eastern"
_token: "Fixv8PZsW6vsavjysdbVcxDsedqy8tiw7s7vUVBp"


Solution 1:[1]

We cant use replace on objects.It can be used on strings.If you want to replace the values of object you can loop through object and use replace on single values.

Yoc can try this method to get values of an object:

for (const [key, value] of Object.entries(reportDropDownsJson)) {
  console.log(`${key}: ${value}`);
}

Inside for loop you can use value.replace() and do whatever logic

Solution 2:[2]

Replace cannot be used in objects.

To iterate the keys and values inside an object, you can do this:

Object.entries(reportDropDownsJson).forEach(([key, value]) => {
    // Do whatever you need to write out the json with the "key" and "value" pair
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user2528260