将字符串数组转换为JAVASCRIPT对象

时间:2019-10-30 13:16:35

标签: javascript arrays

我遇到问题,我将字符串数组设置为

[
    "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:"
]

我需要将其转换为对象

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

同样。

JSON.parse不适用于非序列化字符串。

4 个答案:

答案 0 :(得分:3)

使用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)

答案 1 :(得分:1)

类似的事情应该起作用:

input.map(v => v.split(',').map(v => {
    const [key, ...value] = v.split(':');
    const obj = {};
    obj[key] = value.join(':');
    return obj;
}))

答案 2 :(得分:0)

您可以使用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)

答案 3 :(得分:0)

您必须用逗号和冒号分隔字符串。唯一的问题是您的时间字符串中有一串冒号。这是一个开始。

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