[英]Convert array of string to JAVASCRIPT object
I got problem, I've array of string as我有问题,我有字符串数组
[
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
I need to convert it to Object我需要将其转换为 Object
[
{"Time" : "25/10/2019 14:49:47.41", "Server", "Daniel.Europe..", .. },
{}
]
likewise.同样地。
JSON.parse won't work on non-serialized string. JSON.parse 不适用于非序列化字符串。
Using Object.fromEntries()
使用
Object.fromEntries()
var data = [ "Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:", "Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:" ] var result = data.map(v => Object.fromEntries(v.split(',').map(v => v.split(/:(.*)/))) ) console.log(result)
Something like this should work:像这样的东西应该工作:
input.map(v => v.split(',').map(v => {
const [key, ...value] = v.split(':');
const obj = {};
obj[key] = value.join(':');
return obj;
}))
You can get it using map and reduce:您可以使用 map 获得它并减少:
const arr = [ "Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:", "Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:" ] const newArr = arr.map(item => { return item.split(",").reduce((acc, curr) => { const label = curr.split(":")[0]; const value = curr.substring(label.length+1) acc[curr.split(":")[0]] = value return acc; },{}) }) console.log(newArr)
You have to split your strings by commas and colons.您必须用逗号和冒号分隔字符串。 Only problem is that your time string has a bunch of colons in it.
唯一的问题是您的时间字符串中有一堆冒号。 Here is a start.
这是一个开始。
var a = [ "Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:", "Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:" ]; b = a.map(function(line) { var obj = {}; line.split(",").forEach(function(item) { kv = item.split(/:(.+)/,2); obj[kv[0]]=kv[1]; }); return obj; }); console.log(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.