![]() |
Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects: Table of Content Using JSON.parse() MethodIf the string is in JSON format, you can use the Example: Parsing JSON String to Array of Objects which involves parsing a JSON string into an array of objects and then logging the resulting array.
Output [ { name: 'xyz', age: 30 }, { name: 'abc', age: 25 } ] Using String Splitting and Object ConstructionIf the string is not in JSON format, you can manually split the string and construct objects to create the array, split() method splits the string into an array of individual records based on the semicolon delimiter. The map() is used to iterates over each record and splits it into name and age using the comma delimiter. An object is constructed for each record with name and age properties, and age is converted to an integer using parseInt(age). Example: Converting String Records to Array of Objects it involves splitting a string of records, mapping each record to an object with name and age properties, and then logging the resulting array of objects.
Output [ { name: 'xyz', age: 30 }, { name: ' abc', age: 25 } ] Using Regular ExpressionsFor more complex string formats, you can use regular expressions to extract data and convert it into an array of objects. The regular expression Example: Converting JSON String to Array of Objects it involves parsing a JSON string into an array of objects.
Output [ { name: 'xyz', age: 30 }, { name: 'abc', age: 25 } ] Using Custom Delimiters and Object ConstructionAnother approach to convert a string to an array of objects is to use custom delimiters and object construction. This method is particularly useful when the string format doesn’t follow a strict JSON structure but contains well-defined patterns or delimiters. By splitting the string based on these custom delimiters, we can construct objects and create the desired array. Example: The following example demonstrates how to convert a string with custom delimiters into an array of objects.
Output [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Bob', age: 35 } ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |