How to Convert String to Array of Objects JavaScript ?
Last Updated :
30 Aug, 2024
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:
Using JSON.parse() Method
If the string is in JSON format, you can use the JSON.parse()
method to convert it into an array of objects. JSON.parse() method converts the JSON string into an array of objects. The string must be in valid JSON format for JSON.parse() to work correctly.
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.
JavaScript
const str =
'[{"name":"xyz", "age":30}, {"name":"abc", "age":25}]';
const arrayOfObjects = JSON
.parse(str);
console.log(arrayOfObjects);
Output[ { name: 'xyz', age: 30 }, { name: 'abc', age: 25 } ]
Using String Splitting and Object Construction
If 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.
JavaScript
const dataString = 'xyz, 30; abc, 25';
const records = dataString
.split(';');
const arrayOfObjects = records
.map(record => {
const [name, age] = record
.split(',');
return { name, age: parseInt(age) };
});
console.log(arrayOfObjects);
Output[ { name: 'xyz', age: 30 }, { name: ' abc', age: 25 } ]
Using Regular Expressions
For more complex string formats, you can use regular expressions to extract data and convert it into an array of objects. The regular expression /Name: ([^,]+), Age: (\d+)/g
is used to match the pattern in the string. The while
loop iterates over each match found by the regular expression. For each match, an object is constructed with name
and age
properties, and age
is converted to an integer using parseInt(match[2])
. The object is then added to the arrayOfObjects
.
Example: Converting JSON String to Array of Objects it involves parsing a JSON string into an array of objects.
JavaScript
const str = 'Name: xyz, Age: 30; Name: abc, Age: 25';
const regex = /Name: ([^,]+), Age: (\d+)/g;
const arrayOfObjects = [];
let match;
while ((match = regex
.exec(str)) !== null) {
arrayOfObjects
.push({
name: match[1],
age: parseInt(match[2])
});
}
console.log(arrayOfObjects);
Output[ { name: 'xyz', age: 30 }, { name: 'abc', age: 25 } ]
Using Custom Delimiters and Object Construction
Another 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.
JavaScript
const inputString = "name:John,age:30|name:Jane,age:25|name:Bob,age:35";
function stringToArrayOfObjects(str) {
return str.split('|').map(record => {
const properties = record.split(',');
const obj = {};
properties.forEach(property => {
const [key, value] = property.split(':');
obj[key.trim()] = isNaN(value) ? value.trim() : parseInt(value);
});
return obj;
});
}
const arrayOfObjects = stringToArrayOfObjects(inputString);
console.log(arrayOfObjects);
Output[
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 }
]
Using Mapping and Filtering Functions
This method involves using map
and filter
functions to handle strings with a custom format, which can be especially useful if you need to preprocess the data before constructing objects.
Example: In this example we defines a function to parse a string of records into an array of objects. It splits the input string by ;, processes each record, and handles properties to create the final array.
JavaScript
const inputString = "Name:John, Age:30; Name:Jane, Age:25; Name:Bob, Age:35";
function parseStringToArrayOfObjects(str) {
const records = str.split(';').map(record => record.trim()).filter(Boolean);
const objectsArray = records.map(record => {
const properties = record.split(',').map(prop => prop.trim());
const obj = properties.reduce((acc, property) => {
const [key, value] = property.split(':').map(part => part.trim());
acc[key] = isNaN(value) ? value : parseInt(value, 10);
return acc;
}, {});
return obj;
});
return objectsArray;
}
const arrayOfObjects = parseStringToArrayOfObjects(inputString);
console.log(arrayOfObjects);
Output[
{ Name: 'John', Age: 30 },
{ Name: 'Jane', Age: 25 },
{ Name: 'Bob', Age: 35 }
]
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read