Convert string with separator to array of objects in JavaScript


In this article we will discuss algorithm and complexity for converting string with separator to array of objects with the help of Javascript functionalities. For doing this task we will use split and map functions of Javascript.

Understanding the problem statement

The problem statement says to write a function which can convert a given string with the given separator into an array of objects in Javascript. For example, if we have a string "name1, name2, name3" and a separator "," then we have to convert these strings into an array of objects which looks like:

[{value: "name1"}, {value: "name2"}, {value: "name3"}]

The resultant array will have an object for every value in the given input string where each object has a single property called "value" with the corresponding value from the given input string.

Logic for the given problem

In the code we will include a split method to split the given string into an array of values with the help of a separator. After that we will use map method to create a new object for every value in the resultant array with the "value" property set to the corresponding value. The result will be an array of objects.

Algorithm

Step 1: Define a function to convert string with separator to array of objects. And pass arguments first is string and the second is separator.

Step 2: Use a variable to store the splitted string of values with the help of split method..

Step 3: Now with the help of map method create a new object for every value for the resultant array.

Step 4: Return the resultant array of objects with key and value pairs.

Example

//function to convert a string into a object array
function convertStringToObjectArray(str, separator) {
  const splitStr = str.split(separator);
  const objArray = splitStr.map((val) => {
   return { value: val };
  });
  return objArray;
}
const inputString = "Jiya,Deepak,Anmol,Smita";
const separator = ",";
const objectArray = convertStringToObjectArray(inputString, separator);

console.log(objectArray);

Output

[
  { value: 'Jiya' },
  { value: 'Deepak' },
  { value: 'Anmol' },
  { value: 'Smita' }
]

Complexity

The time complexity for the solution is O(n) in which n is the length of the given input string. Because we have used a function which is performing a task to split a string and then iterating over the resulting array to create the object array.

Conclusion

So overall we can say this is the good approach to get the transformed data. In this problem statement we have asked to solve a common task to convert a string with a separator into a structured data format in Javascript.

Updated on: 14-Aug-2023

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements