0

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

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome. See the other option I've added, and don't forget to accept the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.