mburke05
mburke05

Reputation: 1471

Javascript converting object property to string using JSON.stringify() returning object

I have an array of objects, like so:

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 am attempting to convert the nested objects into strings for a CSV parsing program however when using the following code:

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

after checking typeof(item.response) for an item in my array, i still get returned object.

However, if I manually set the property of the individual item, outside a for loop, it appears to work as intended.

e.g.

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

Upvotes: 0

Views: 112

Answers (1)

Ori Drori
Ori Drori

Reputation: 192317

When you use for...in the item is the index, and not the object itself. Instead Use for...of, that will assign the value to item:

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}}];

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

console.log(arr);

If you don't want to mutate your data, Array#map would create a new array, with new objects, instead of changing the originals:

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}}];

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

console.log(result);

Upvotes: 2

Related Questions