简体   繁体   中英

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. Then you can simply call JSON.parse() and work with the resulting array as needed. 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"]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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