JavaScript ES6将嵌套的分隔字符串解析为键/值

时间:2018-11-20 23:44:03

标签: javascript arrays regex string object

我有以下对象数组:

var addresses = [ 
  { ResourceId: 2,
    OfficeAddress:
     '20 Main Street\r\nRiverside\r\nUSA' },
  { ResourceId: 191,
    OfficeAddress:
     '20 Main Street\r\nRiverside\r\nUSA' },
  { ResourceId: 204,
    OfficeAddress:
     '20 Main Street\r\nRiverside\r\nUSA' }
]

我想尝试将字符串拆分为对象内它们自己的键/值对:

[ 
  { ResourceId: 2,
    address1: "20 Main Street",
    address2: "Riverside",
    address3: "USA"
    },
  { ResourceId: 191,
    address1: "20 Main Street",
    address2: "Riverside",
    address3: "USA"
    },
  { ResourceId: 204,
    address1: "20 Main Street",
    address2: "Riverside",
    address3: "USA"
    }
]

如果它只是正常普通字符串,我可以执行以下操作:

let output = addresses.split("\r").reduce(function(
        obj,
        str,
        index
      ) {
        let strParts = str.split(":");
        obj[strParts[0].replace(/\s+/g, "")] = strParts[1];
        return obj;
      },
      {});

有人会知道如何遍历数组中的每个对象并将字符串拆分为3个地址值/键吗?也许是.map?

1 个答案:

答案 0 :(得分:3)

我认为map()是可行的方法,因为您希望每个输入都有一个包含项的数组。每次迭代都创建一个新对象:

var addresses = [ { ResourceId: 2,OfficeAddress:'20 Main Street\r\nRiverside\r\nUSA' },{ ResourceId: 191,OfficeAddress:'20 Main Street\r\nRiverside\r\nUSA' },{ ResourceId: 204,OfficeAddress:'20 Main Street\r\nRiverside\r\nUSA' }]

let newArray= addresses.map(({ResourceId,OfficeAddress }) => {
    let [address1, address2, address3] = OfficeAddress.split('\r\n')
    return {ResourceId, address1, address2, address3}
})
console.log(newArray)

您还可以考虑将地址保存在数组中,而不是单独命名的属性:

var addresses = [ { ResourceId: 2,OfficeAddress:'20 Main Street\r\nRiverside\r\nUSA' },{ ResourceId: 191,OfficeAddress:'20 Main Street\r\nRiverside\r\nUSA' },{ ResourceId: 204,OfficeAddress:'20 Main Street\r\nRiverside\r\nUSA' }]

let newArray= addresses.map(({ResourceId,OfficeAddress }) => {
    let address = OfficeAddress.split('\r\n')
    return {ResourceId, address}
})
console.log(newArray)