Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate js key-value object from string

I got a very common question but with a twist which is the reason for this post:

I want to create a key,value object from a string.

my string looks like this:

01§§foo§§bar§§someLink

(i can change the delimiter symbols to whatever i want, if there should be somehow a very tight solution with a specific symbol)

now, i want a key value object and most questions about this problem already got the datapair in the string,(like "id:01,title:foo") but thats not the case in my problem.

i want to generate something like this:

var modules = [
{"ID":"01", "title":"foo", "description":"bar","link":"someLink"},
//more entries from more strings
];

the reason for the key,value object is, that there are more of these strings which I convert from a database. I want it to be in a key,value object so its easier to work with the data later in my tool.

Thank you in advance

like image 263
Martin WasGehtSieDasAn Avatar asked Sep 29 '26 23:09

Martin WasGehtSieDasAn


1 Answers

You could use Array#split for the string and an array for the keys.

var string = '01§§foo§§bar§§someLink',
    moduleKeys = ["ID", "title", "description", "link"],
    object = {};

string.split('§§').forEach(function (a, i) {
    object[moduleKeys[i]] = a;
});

console.log(object);

A methode for multiple strings.

function getData(array) {
    var moduleKeys = ["ID", "title", "description", "link"];
    return array.map(function (string) {
        var object = {};
        string.split('§§').forEach(function (a, i) {
            object[moduleKeys[i]] = a;
        });
        return object;
    });
}

var strings = ['01§§foo§§bar§§someLink', '02§§foo§§bar§§someLink'];
console.log(getData(strings));
like image 76
Nina Scholz Avatar answered Oct 01 '26 13:10

Nina Scholz