0

I have an array of objects that looks like this:

[ { color: 'red',
    direction: { width: 1, height: 3 },
    alpha: 0.5,
    blur: 3 },
  { color: 'green',
    direction: { width: 1, height: 9 },
    alpha: 0.09,
    blur: 11 } ]

I need to insert it into a string that looks like this:

'exports.' + name + ' = ' + ARRAY_ABOVE_HERE + ';'

So that the final outcome — what gets written to a file — is this:

exports.shadow = [
  {
    color: 'red',
    direction: { width: 1, height: 3 },
    alpha: 0.5,
    blur: 3
  },
  {
    color: 'green',
    direction: { width: 1, height: 9 },
    alpha: 0.09,
    blur: 11
  }
];

What happens currently is the [object Object] deal (exports.shadow = [object Object],[object Object];). I thought JSON.parse() might be what I'm looking for but no luck there.

Is there some utility or pattern I'm missing that does this? Or do I need to just reconstruct it by mapping the array and manually concatenating the properties with the values?

David Yeiser
  • 1,438
  • 5
  • 22
  • 33

1 Answers1

0

You can just do it using JSON.stringify( object, null, '\t' ) as seen in this sample

const content = [ { color: 'red',
    direction: { width: 1, height: 3 },
    alpha: 0.5,
    blur: 3 },
  { color: 'green',
    direction: { width: 1, height: 9 },
    alpha: 0.09,
    blur: 11 } ];
    
console.log( 'exports.shadow = ' + JSON.stringify( content, null, '\t' ) + ';');
Icepickle
  • 12,689
  • 3
  • 34
  • 48