Sunday, 16 April 2017

Make an object's property display as color in the terminal

Is it possible to do this? I wanted to use the npm module chalk and color a property so that when I JSON.stringify it and display the object contents in the terminal the property values will display as a color of my choosing so that its easier to read.

I was thinking something like:

const arrObjects = [
  {
    color: 'red',
    fruit: 'apple'
  },
  {
    color: 'pink',
    fruit: 'dragonfruit'
  }
];

const coloredProps = arrObjects.map(fruit => {
  Object.defineProperty(fruit, chalk.yellow.bold('family'), {
    value: 'healthy',
    writeable: true,
    configurable: true,
    enumerable: true
  });
});

console.log(JSON.stringify(arrObjects, null, 2));

So it would display the new property family in yellow

Which almost seems like I was getting there but the problem is that in the terminal it displays the property as a unicode because of the JSON.stringify. Is there a way to get passed this?

here is my result:

enter image description here



via Chris

No comments:

Post a Comment