简体   繁体   English

Javascript:如何将字符串转换为对象数组

[英]Javascript: How can I turn a String into an array of objects

I have a string formatted as below:我有一个格式如下的字符串:

{"title":"XYZ","id":"123"} {"title":"NPS","id":"124"}{"title":"LMW","id":"125"}

I am trying to convert this into an array by storing it in a variable and splitting it as such:我试图通过将其存储在一个变量中并将其拆分为这样的数组来将其转换为数组:

let prodInfo = "{"title":"XYZ","id":"123"} {"title":"NPS","id":"124"}{"title":"LMW","id":"125"}";

I then split this variable as in:然后我将这个变量拆分为:

   let infoArry =  prodInfo.split("}");
   console.log(infoArry);

The results I get after this is:我得到的结果是: 在此处输入图片说明

The issue is when I loop through this array to access titles separately, I get it as undefined.问题是当我遍历这个数组来分别访问标题时,我得到它为未定义。

Any recommendations would be appreciated任何建议将不胜感激

Given that you state in the comments under the question that you are able to change the input string format, I would strongly suggest you convert it to valid JSON.鉴于您在问题下的评论中声明您可以更改输入字符串格式,我强烈建议您将其转换为有效的 JSON。 Then you can simply call JSON.parse() and work with the resulting array as needed.然后您可以简单地调用JSON.parse()并根据需要处理结果数组。 Try this:尝试这个:

 var input = '[{"title":"XYZ","id":"123"},{"title":"NPS","id":"124"},{"title":"LMW","id":"125"}]'; var output = JSON.parse(input); output.forEach(obj => console.log(obj.title)); // just an example

const input = '{"title":"XYZ","id":"123"} {"title":"NPS","id":"124"}{"title":"LMW","id":"125"}'; const objects = input.split("}").filter(element => !!element).map(element => JSON.parse(element + "}"));; objects.forEach(object => console.log(object["title"]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM