简体   繁体   中英

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

[
    {"Time" : "25/10/2019 14:49:47.41", "Server", "Daniel.Europe..", .. },
    {}
]

likewise.

JSON.parse won't work on non-serialized string.

Using 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM