从数组元素中删除字符串符号

时间:2020-05-13 14:25:14

标签: javascript jquery arrays angularjs

我有一个数组

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' }"]

我需要这样的输出数组

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' }]

我尝试过

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

但是它给出了不确定的信息。我该如何解决?

1 个答案:

答案 0 :(得分:2)

我们可以通过使用字符串构造函数创建函数来实现此目的(这与使用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; }