Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating an array using a string which contains the key and the value of the properties - JavaScript
Suppose, we have a special kind of string like this ?
const str = "Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";
We are required to write a JavaScript function that converts the above string into an array of objects, using the String.prototype.split() method ?
const arr = [
{
"Integer": 1,
"Float": 2.0
},
{
"Boolean": true,
"Integer": 6
},
{
"Float": 3.66,
"Boolean": false
}
];
Parsing Rules
We have to use the following rules for conversion ?
-
marks the end of an object - One whitespace terminates one key/value pair within an object
- Comma separates the key from value of an object
Method 1: Basic String Splitting
The initial approach splits the string but doesn't merge key-value pairs into single objects:
const str = "Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";
const stringToArray = str => {
const strArr = str.split('
');
return strArr.map(el => {
const elArr = el.split(' ');
return elArr.map(elm => {
const [key, value] = elm.split(',');
return {
[key]: value
};
});
});
};
console.log(JSON.stringify(stringToArray(str), null, 2));
[
[ { "Integer": "1" }, { "Float": "2.0" } ],
[ { "Boolean": "True" }, { "Integer": "6" } ],
[ { "Float": "3.66" }, { "Boolean": "False" } ]
]
Method 2: Creating Single Objects (Improved)
To create single objects instead of arrays of objects, we need to merge the key-value pairs:
const str = "Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";
const stringToObjectArray = str => {
const lines = str.split('
');
return lines.map(line => {
const pairs = line.split(' ');
const obj = {};
pairs.forEach(pair => {
const [key, value] = pair.split(',');
// Convert string values to appropriate types
if (value === 'True' || value === 'true') {
obj[key] = true;
} else if (value === 'False' || value === 'false') {
obj[key] = false;
} else if (!isNaN(value) && !isNaN(parseFloat(value))) {
obj[key] = parseFloat(value);
} else {
obj[key] = value;
}
});
return obj;
});
};
console.log(JSON.stringify(stringToObjectArray(str), null, 2));
[
{ "Integer": 1, "Float": 2 },
{ "Boolean": true, "Integer": 6 },
{ "Float": 3.66, "Boolean": false }
]
Method 3: Using Object.assign() for Merging
Alternative approach using Object.assign() to merge key-value pairs:
const str = "Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";
const convertStringToArray = str => {
return str.split('
').map(line => {
const keyValuePairs = line.split(' ').map(pair => {
const [key, value] = pair.split(',');
// Type conversion
let convertedValue;
if (value === 'True') convertedValue = true;
else if (value === 'False') convertedValue = false;
else if (!isNaN(value)) convertedValue = Number(value);
else convertedValue = value;
return { [key]: convertedValue };
});
return Object.assign({}, ...keyValuePairs);
});
};
console.log(JSON.stringify(convertStringToArray(str), null, 2));
[
{ "Integer": 1, "Float": 2 },
{ "Boolean": true, "Integer": 6 },
{ "Float": 3.66, "Boolean": false }
]
Key Points
-
split('separates each object definition
') -
split(' ')separates key-value pairs within each line -
split(',')separates keys from values - Type conversion is important for proper data types (numbers, booleans)
- Object.assign() or forEach can merge multiple key-value pairs into single objects
Conclusion
Converting structured strings to arrays of objects requires careful parsing and type conversion. The improved methods create proper objects with correct data types instead of arrays of single-property objects.
