特殊格式字符串转为数组对象


Name                       : 以太网 3
InterfaceDescription       : 
InterfaceIndex             : 11
MacAddress                 : *
MediaType                  : 802.3
PhysicalMediaType          : Unspecified
InterfaceOperationalStatus : NotPresent
AdminStatus                : Down
LinkSpeed(Mbps)            : 0
MediaConnectionState       : Unknown
ConnectorPresent           : False
DriverInformation          : ""

Name                       : 以太网 2
InterfaceDescription       : 
InterfaceIndex             : 8
MacAddress                 : **
MediaType                  : 802.3
PhysicalMediaType          : Unspecified
InterfaceOperationalStatus : Up
AdminStatus                : Up
LinkSpeed(Gbps)            : 1
MediaConnectionState       : Connected
ConnectorPresent           : True
DriverInformation          : ""

js或jquery如何将这样的字符串转为正常的数组对象,求指教!

function strToArray(str) {
  const res = []
  const groups = str.split(/\n/)
  let obj = {}
  for (const group of groups) {
    const groupWithoutWhite = group.replace(/\s+/g, '')
    if (groupWithoutWhite) {
      const [ key, value ] = groupWithoutWhite.replace(/(""|'')/g, '').split(':')
      obj[key] = value
    } else {
      if (Object.keys(obj).length) {
        res.push(obj)
      }
      obj = {}
    }
  }
  if (Object.keys(obj).length) {
    res.push(obj)
  }
  return res
}

const str = `
Name                       : 以太网 3
InterfaceDescription       :
InterfaceIndex             : 11
MacAddress                 : *
MediaType                  : 802.3
PhysicalMediaType          : Unspecified
InterfaceOperationalStatus : NotPresent
AdminStatus                : Down
LinkSpeed(Mbps)            : 0
MediaConnectionState       : Unknown
ConnectorPresent           : False
DriverInformation          : ""

Name                       : 以太网 2
InterfaceDescription       :
InterfaceIndex             : 8
MacAddress                 : **
MediaType                  : 802.3
PhysicalMediaType          : Unspecified
InterfaceOperationalStatus : Up
AdminStatus                : Up
LinkSpeed(Gbps)            : 1
MediaConnectionState       : Connected
ConnectorPresent           : True
DriverInformation          : ""`


console.log(strToArray(str))

首先可以看出实例中是两部分完全一样的,应该变成数组。数组中对象肯定是要按照 “ :”来分隔的

for i in data
arr.push(
{
i: data[i].
}
)