Languages

JavaScript - convert string to object

0 points
Asked by:
illona
526

How to convert string to object in JavaScript?

Let's say I have the following string:

var text = 'id:1, name:Kate';

and I need to convert it to:

var object = { id: 1, name: 'Kate' };
2 answers
0 points
Answered by:
illona
526

Solution 1

Assuming that your text is JSON string:

var text = '{"id":"1", "name":"Kate"}';

You can use JSON.parse() method:

// ONLINE-RUNNER:browser;

var text = '{"id":"1", "name":"Kate"}';

var object = JSON.parse(text);

console.log(object.id); // 1
console.log(object.name); // Kate

Solution 2

For a custom string in your case you can use split() method with a simple for loop to add properties to an empty object:

// ONLINE-RUNNER:browser;

var text = 'id:1, name:Kate';

var parts = text.split(', ');
var object = {};

for (var i = 0; i < parts.length; ++i) {
    var tmp = parts[i].split(':');
    object[tmp[0]] = tmp[1];
}

console.log(object.id);   // '1'
console.log(object.name); // 'Kate'

Note:

This solution will give you property values as strings, even if they are booleans, numbers, etc. (e.g '1' instead of 1).

Note:

This solution assumes there are no ':' characters in the property name and value.

 

References

  1. String.prototype.split() - JavaScript | MDN
0 comments Add comment
0 points
Answered by:
illona
526

Here is a solution that splits the text into parts, removing whitespace. Then creates key/value pair for each part (also omitting whitespace). In next step it checks for duplicate keys because objects cannot have duplicated properties. At the end it creates the result object.

// ONLINE-RUNNER:browser;

var PART_EXPRESSION = /\s*,\s*/;
var PAIR_EXPRESSION = /\s*:\s*/;

function parseText(text) {
    var parts = text.split(PART_EXPRESSION);
    var object = {};
    for (var i = 0; i < parts.length; ++i) {
        var part = parts[i];
        if (part) {
            var pair = part.split(PAIR_EXPRESSION);
            var key = pair[0];
            if (key in object) {
                throw new Error('Text contains duplicated keys.');
            }
            var value = '';
            if (pair.length > 0) {
                value += pair[1];
                for (var j = 2; j < pair.length; ++j) {
                    value += ':' + pair[j];
                }
            }
            object[key] = value;
        }
    }
    return object;
}


// Usage example:

var text = 'id:1, name:Kate:5, age:29';
var object = parseText(text);

console.log(object.id);
console.log(object.name);
console.log(object.age);
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join