Reputation: 1200
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.
Upvotes: 1
Views: 89
Reputation: 2031
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);
Upvotes: 0
Reputation: 529
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)
Upvotes: 0
Reputation: 20039
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)
Upvotes: 3
Reputation: 443
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;
}))
Upvotes: 1