Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从数组元素中删除字符串符号_Javascript_Jquery_Arrays_Angularjs - Fatal编程技术网

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

Javascript 从数组元素中删除字符串符号,javascript,jquery,arrays,angularjs,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' }"] 我需要这样的输出数组 expectedRes

我有一个数组

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

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

我们可以通过使用字符串构造函数创建函数(这与使用eval不同):

constmyarray=[“{depth:1,display:'X'}”,“{depth:2,display:'X.X'}”,“{depth:3,display:'X.X'}”,“{depth:4,display:'X.X.X'}”,“{depth:5,display:'X.X.X'}”,“{depth:6,display:'X.X.X.X.X'}];
常量myOutput=myArray.map(项=>{
/* 
*根据mozilla使用的函数(“返回某物”)
*比eval()更好-并且不使用eval
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!
*/ 
return(新函数('return'+项))();
})
console.log(myOutput)

.as控制台包装{max height:100%!important;top:0;}
您想要的是
JSON.parse()
,而不是
JSON.stringify
。也就是说,它不会工作,因为数组中的字符串不是有效的JSON。您需要修改它们,使其成为有效的JSON,但是如果您可以编辑响应,那么完全不使用JSON就更有意义了;JSON.stringify(x)给出
'{“depth”:1,“display”:“x”}'
如果它只是且始终是“depth”和“display”,您可以使用RegEx提取值并创建新对象。您不需要
JSON.parse()
或RegEx,您可以使用
arr.map(item=>(new Function('return'+item)))来完成它。
,这对任何对象都是灵活的,JavaScript可以解析字符串格式的对象。这不是我的意图,但我可以看到你是如何像那样读取它的。我道歉。我应该用“X&Y的替代品是Z”来表达。我不是有意冒犯你的。我只是想指出Javascript有一种强大的方法来解析字符串。实现结果总是有几种方法。一个不能使另一个无效。