gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:16:15 25 4
gpt4 key购买 nike

我有以下对象数组:

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?

最佳答案

我认为 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)

关于JavaScript ES6 将嵌套分隔字符串解析为键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53403278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com