gpt4 book ai didi

javascript - 有人可以帮我在 javascript 中将字符串转换为对象吗

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

var str="Segment Id : 82394 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01 | Segment 
Count : 0 Segment Id : 82395 |
Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (LeadYoung)_02 | Segment Count : 0
Segment Id : 82395 |
Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (LeadYoung)_02 | Segment Count : 0"

我想将其转换为类似的对象

[{    
SegmentId : 82394,
SegmentName: Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01,
SegmentCount: 0
},
{
SegmentId : 82394,
SegmentName: Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01,
SegmentCount: 0
}
]

最佳答案

我正在考虑使用分隔符/n 的字符串

var string="Segment Id : 82394 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01 | Segment Count : 0 /n  Segment Id : 82395 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (LeadYoung)_02 | Segment Count : 0"


var separatedAsArray=string.split('/n')
var string2=separatedAsArray.toString();

//Output of the above two lines
"Segment Id : 82394 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01 | Segment Count : 0 , Segment Id : 82395 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (LeadYoung)_02 | Segment Count : 0"


var formatedString = string2.split(',');

//Output of the above line is
["Segment Id : 82394 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01 | Segment Count : 0 ", " Segment Id : 82395 | Segment Name : SPA FIAT MAR 2020 LKADCLAKSC DEM (LeadYoung)_02 | Segment Count : 0"]


formatedString.forEach(function(element) {
var properties = element.split('|');
var obj = {};
properties.forEach(function(ele) {
var keyValue = ele.split(':');
obj[keyValue[0]] = keyValue[1];
});
console.log(obj)
});

//Output of the above code snippet is
{
Segment Count : " 0 ",
Segment Name : " SPA FIAT MAR 2020 LKADCLAKSC DEM (Permission)_01 ",
Segment Id : " 82394 "
}
{
Segment Id : " 82395 ",
Segment Count : " 0",
Segment Name : " SPA FIAT MAR 2020 LKADCLAKSC DEM (LeadYoung)_02 "
}

获取单个对象后,将它们存储在数组中或任何您想要的地方...

关于javascript - 有人可以帮我在 javascript 中将字符串转换为对象吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61080622/

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