Using JSON.stringify() in Javascript to convert object property to a string results in returning the object as

I have an array of objects that I need to convert into strings for a CSV parsing program. The array looks like this:

var arr = [{request: {funding : 123, id: 123abc, membership: true},
response: {funding : 285, success: true }},
{request: {funding : 123, id: 123def, membership: true},
response: {funding : 167, success: true }},
{request: {funding : 123, id: 123def, membership: true},
response: {funding : 234, success: true }}]

I tried using a loop to convert the nested objects into strings using JSON.stringify(), but it didn't seem to work as expected:

for (var item in arr) 
    { item.response = JSON.stringify(item.response);
      item.request = JSON.stringify(item.request);
}

Even after running this code, checking the type of item.response still returns object.

However, when manually setting the property of an individual item outside of the loop, it does work correctly:

arr[0].response = JSON.stringify(arr[0].response)
typeof(arr[0].response) // string

Answer №1

When using for...in, keep in mind that the item refers to the index, not the actual object itself. To access the value of item, consider using for...of instead:

var data = [{"request":{"funding":123,"id":"123abc","membership":true},"response":{"funding":285,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":167,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":234,"success":true}}];

for (var item of data) {
    item.response = JSON.stringify(item.response);
    item.request = JSON.stringify(item.request);
}

console.log(data);

To prevent mutating your original data, you can use Array#map to create a new array with new objects:

var data = [{"request":{"funding":123,"id":"123abc","membership":true},"response":{"funding":285,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":167,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":234,"success":true}}];

var result = data.map(function(item) {
  return {
    response: JSON.stringify(item.response),
    request: JSON.stringify(item.request)
  };
});

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Restify displays an error message stating that undefined is not a function

I am encountering a custom Restify error that is being thrown to the catch block of BlueBird Promise. var test = function() { respObject = { hello: { world: 'aasas' } }; throw new restify.errors.ServiceError(respObject, 422); } Then in Ser ...

Getting Your Redux Form Ready for Submission

I recently transformed my Redux form into a wizard with multiple subcomponents following the structure outlined here: However, I'm encountering difficulties when trying to integrate the form with my actions to submit the form data. Unlike the example ...

Slider handle for Material UI in React component reaches the range value

In my application, I am using a range slider component from material-UI. The main page displays a data table with the fields: id, name, current price, new price. The current price for each item is fixed, but the new price will be determined based on the s ...

Discovering the identification of a comment in JavaScript

Here is the code snippet I am working with: <a onclick="lel($(this),'212345555')" class="button"> <a onclick="lel($(this),'241214370')" class="button"> <a onclick="lel($(this),'248916550')" class="button"> & ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

Loop through an HTML table in order to emphasize variations in cells that contain multiple comparison items

I am interested in highlighting variances between the initial row of a table and all other rows based on columns. I have successfully managed to achieve this when each cell contains only one item/comparison. However, I would like to expand this to include ...

What is the best way to showcase a PDF in Django that is saved as a blob in a MySQL database?

Within my web application, users have the ability to upload a PDF file which is then stored directly in the MySQL database for security reasons. Utilizing the code snippet below, this process allows the uploaded file to be safely saved within the database ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Implementing Othello Minimax Algorithm in React.js Yields Unsuccessful Results

I need assistance with a recurring issue where the AI player consistently plays the first available move it encounters. My objective was to implement an AI using the Minimax Algorithm, but I'm facing challenges in achieving the desired functionality. ...

Is it possible for Cypress to execute test files that are imported from outside of the Cypress folder

Currently, I am developing an E2E test framework using Cypress and encountered an issue while trying to import spec files from locations outside the traditional Cypress directory structure (which includes directories for fixtures, integration, plugins, and ...

Struggling to properly parse JSON data using jQuery

I am a beginner in jquery and have a php script that returns JSON data. However, I am facing an issue while trying to fetch and process the result using jquery. Below is the code snippet: calculate: function(me, answer, res_id, soulmates) { conso ...

What are the steps to create an object from an array?

Is it possible to create an object from an array in TypeScript? { A: {H: 10, W: 20, S: 30}} using the following data: [ { group: A, name: H, value: 10 }, { group: A, name: W, value: 20}, { group: A, name: S, value: 30} ] L ...

What is the proper way to include a URL when submitting an AJAX form?

When I try to call a servlet using HTML, jQuery and Ajax by submitting a form, I keep getting a 404 error saying the resource cannot be found. My project is built with Maven. The Servlet is located in the src/main/java package under : com.mycompany.sample ...

Error encountered: Nitrogen is undefined

For the past three years, my Nitrogen web framework powered site has been functioning smoothly across all browsers. However, I recently encountered an issue where postbacks would randomly fail to respond in Google Chrome and Opera, with the console display ...

Removing a document from Firestore using React

Is there a way to delete a document in Firestore without knowing the document ID? If I only have the name of the document, how can I go about deleting it? This is how I currently export the database: export const db = getFirestore(app) I feel like I nee ...

Trim the name property of an object within an object's map function if it exceeds a certain length

Imagine having an object structured like this: var fullObj = { prop1: "myProp1", subobject: { Obj1_id: { id: "Obj3_id", name: "./", otherProperties:... }, Obj2_id: { id: "Obj2_id&q ...

Tips for displaying multiple real-time data markers on a Mapbox map using a PHP file

In my PHP code, I have implemented a system that updates real-time data on my Mapbox map. Here is an excerpt of the code: $value = array( "geometry"=>array( "type"=> "Point", "coordinates"=> [floatval($longitude),floatval($ ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...