【问题标题】:Remove string sign from array element从数组元素中删除字符串符号
【发布时间】:2020-08-29 19:07:01
【问题描述】:

我有一个数组

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;
             })

但它给出了未定义的。我该如何解决这个问题?

【问题讨论】:

  • 你想要JSON.parse(),而不是JSON.stringify。话虽如此,它不会起作用,因为数组中的字符串不是有效的 JSON。您需要修改它们以使它们成为有效的 JSON,然而如果您可以编辑响应,那么根本不使用 JSON 会更有意义。跨度>
  • 向后工作以获得您需要的“JSON”:var x = { depth:1, display:"x" };JSON.stringify(x) 提供'{"depth":1,"display":"x"}'
  • 如果只有并且总是“深度”和“显示”,您可以使用 reg ex 提取值并创建一个新对象。
  • 你不需要JSON.parse()或者RegEx,你可以用arr.map(item => (new Function('return ' + item))() )来做,它对任何对象都很灵活,是JavaScript可以解析的字符串格式。
  • 这不是我的本意,但我知道你怎么能这样读。我很抱歉。我应该将其表述为“X 和 Y 的替代方案是 Z”。没有冒犯你的意思。我只是想指出,Javascript 有一种强大的方式来解析字符串。总有几种方法可以达到结果。一个不会使另一个无效。

标签: javascript jquery arrays angularjs


【解决方案1】:

我们可以通过使用字符串构造函数创建一个函数来做到这一点(这与使用 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; }

【讨论】:

    猜你喜欢
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多