从命名索引JS获取数组值

时间:2022-07-22 21:16:51

I have a JS variable that receive a serialized C# List with JavaScriptSerializer.

我有一个JS变量,它接收带有JavaScriptSerializer的序列化C#List。

The string passed to the JS variable after serialization is like this :

串行化后传递给JS变量的字符串如下所示:

{"Date":"April 2017 - April 2017","Source":"Foo","Type":"Bar","Value":14}{"Date":"April 2017 - April 2017","Source":"Foo","Type":"Bar","Value":14}

I would like to put all the "Values" in an array x and all the "Date" in an array y.

我想将所有“值”放在数组x中,将所有“Date”放在数组y中。

When i do x: source["Date"] and y: source["Value"], x and y stay empty.

当我执行x:source [“Date”]和y:source [“Value”]时,x和y保持为空。

Why is that ?

这是为什么 ?

1 个解决方案

#1


2  

Your Json is not properly formatted, however if you correct it into the proper Json format you can use JavaScript map to accomplish what you need.

您的Json格式不正确,但是如果您将其更正为正确的Json格式,则可以使用JavaScript map来完成您的需要。

let arr = '[{"Date":"April 2017 - April 2017","Source":"Foo","Type":"Bar","Value":14},
          {"Date":"April 2017 - April 2017","Source":"Foo","Type":"Bar","Value":14}]';

let source = JSON.parse(arr);

let x = source.map(x=> x.Date);
let y = source.map(x=> x.Value);

console.log(x);
//[ 'April 2017 - April 2017', 'April 2017 - April 2017' ]

console.log(y);
//[ 14, 14 ]

#1


2  

Your Json is not properly formatted, however if you correct it into the proper Json format you can use JavaScript map to accomplish what you need.

您的Json格式不正确,但是如果您将其更正为正确的Json格式,则可以使用JavaScript map来完成您的需要。

let arr = '[{"Date":"April 2017 - April 2017","Source":"Foo","Type":"Bar","Value":14},
          {"Date":"April 2017 - April 2017","Source":"Foo","Type":"Bar","Value":14}]';

let source = JSON.parse(arr);

let x = source.map(x=> x.Date);
let y = source.map(x=> x.Value);

console.log(x);
//[ 'April 2017 - April 2017', 'April 2017 - April 2017' ]

console.log(y);
//[ 14, 14 ]