Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation of object with key/value pairs in a string?

I have the following string:

person:juan&age:24&knowledge:html

The problem is that sometimes the string is:

knowledge:html&person:juan&age:24

And it can change the position of the keys and the values.

In this case I would write something like this:

const keys = ["person", "age", "knowledge"];
const keyAndValues = "person:juan&age:24&knowledge:html";

const result = [];

keys.forEach(key => {
  const indexKeyValues = keyAndValues.indexOf(key);
  if (indexKeyValues !== -1) {
    const lastCharIndex = keyAndValues.substring(indexKeyValues).indexOf("&");
    return keyAndValues.substring(indexKeyValues + key.length, lastCharIndex === -1 ? keyAndValues.substring(indexKeyValues).length - 1 || lastCharIndex);
  }
});

But I don't like it and it would be great if I could do something like:

const resultsExpected = /regexGroupedRegardlessOfPosition/g.match("person:juan&age:24&knowledge:html");

console.log(resultsExpected); // { person: "juan", age: 24, knowledge: "html" }
like image 840
juan garcia Avatar asked Dec 19 '22 00:12

juan garcia


2 Answers

Here is a single expression to get the object:

const keyAndValues = "person:juan&age:24&knowledge:html";

const obj = Object.assign(...keyAndValues.split('&').map(s => s.split(':'))
                                         .map(([k, v]) => ({ [k]: v }))
);

console.log(obj);

This uses ES6 destructuring assignment, spread syntax and computed property names.

like image 137
trincot Avatar answered Dec 29 '22 05:12

trincot


You could split the string and then the parts and take the key/values for an object.

function getValues(string) {
    var object = {};
    
    string && string.split('&').forEach(p => {
        var [key, ...value] = p.split(':');
        object[key] = value.join(':');
    });
    return object;
}

console.log(getValues("knowledge:html&person:juan&age:24"));
console.log(getValues("foo:bar:baz&cool:space:aliens:survive"));
console.log(getValues(""));
like image 44
Nina Scholz Avatar answered Dec 29 '22 05:12

Nina Scholz