1

I would like to convert a nested array of Objects into a String. How do I do this?

I have tried the .toString() method but that just returns [Object object], which is not what I want.

My array looks like this:

[[
{"incr":261,"decr":547},
{"incr":259,"decr":549}
],
[{"incr":254,"decr":547}]
]

And I want to be able to convert it into a String that looks exactly like that.

3
  • 3
    Take a look to JSON.stringify() Commented Aug 7, 2019 at 21:22
  • Thanks! That's exactly what I was looking for. Commented Aug 7, 2019 at 21:26
  • You can use space third argument (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) of the JSON.stringify() to format the result with identation: JSON.stringify(data, null, 2) Commented Aug 7, 2019 at 21:46

1 Answer 1

2

Is this what you had in mind?

const data = [
  [{ incr: 261, decr: 547 }, { incr: 259, decr: 549 }],
  [{ incr: 254, decr: 547 }]
];

// like this?
console.log(JSON.stringify(data))
// or maybe like this with some more control over how you generate the string?
console.log(data.reduce((acc, val) => acc.concat(val), []).map(({ incr, decr }) => `Increase: ${incr} - decrease: ${decr}`).join(', '))

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

Comments

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.