Remove string sign from array element

Viewed 74

I am having an array

myArray= ["{ depth: 1, display: 'X' }", "{ depth: 2, display: 'X.X' }", "{ depth: 3, display: 'X.X.X' }", "{ depth: 4, display: 'X.X.X.X' }", "{ depth: 5, display: 'X.X.X.X.X' }", "{ depth: 6, display: 'X.X.X.X.X.X' }"]

I need my output array like this

expectedResult = [{ depth: 1, display: 'X' }, { depth: 2, display: 'X.X' }, { depth: 3, display: 'X.X.X' }, { depth: 4, display: 'X.X.X.X' }, { depth: 5, display: 'X.X.X.X.X' }, { depth: 6, display: 'X.X.X.X.X.X' }]

I tried with this

myArray.map(item => {
               const container = {};
               container[item.depth] = item.display;
               console.log(JSON.stringify(container));
               return container;
             })

But it gives undefined. How can I solve this?

1 Answers

We could do this by creating a function with a string constructor (this is not the same as using eval):

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!

const myArray= ["{ depth: 1, display: 'X' }", "{ depth: 2, display: 'X.X' }", "{ depth: 3, display: 'X.X.X' }", "{ depth: 4, display: 'X.X.X.X' }", "{ depth: 5, display: 'X.X.X.X.X' }", "{ depth: 6, display: 'X.X.X.X.X.X' }"];

const myOutput = myArray.map(item => {
  /* 
   * according to mozilla using Function("return something")
   * is better then eval() - and doesn't use eval
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!
  */ 
  return (new Function('return ' + item))();

})

console.log(myOutput)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related