Creating an object with key / value pairs in a string?

I have the following line:

person:juan&age:24&knowledge:html

The problem is that sometimes the line:

knowledge:html&person:juan&age:24

And he can change the position of the keys and 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" }
+4
source share
6 answers

Here is one 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);
Run codeHide result

It uses ES6 destruction assignment , distribution syntax, and computed property names .

+3
source

You can break the line and then the parts and take the key / values ​​for the 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(""));
Run codeHide result
+3
source
(knowledge|person|age):([^&]+)

, , , :

(\w+):([^&]+)

https://regex101.com/r/HwW5I1/1/

+2

Phiter , , regex . , : " . , ! , ".

&, : :

function strToObject(str) {
  var rv = {};
  str.split("&").forEach(function(substr) {
    var index = substr.indexOf(":");
    if (index === -1) {
      rv[substr] = undefined;
    } else {
      rv[substr.substring(0, index)] = substr.substring(index+1);
    }
  });
  return rv;
}

:

function strToObject(str) {
  var rv = {};
  str.split("&").forEach(function(substr) {
    var index = substr.indexOf(":");
    if (index === -1) {
      rv[substr] = undefined;
    } else {
      rv[substr.substring(0, index)] = substr.substring(index+1);
    }
  });
  return rv;
}

console.log(strToObject("person:juan&age:24&knowledge:html"));
console.log(strToObject("knowledge:html&person:juan&age:24"));
.as-console-wrapper {
  max-height: 100% !important;
}
Hide result

:

  • ES2015 +.
  • (JavaScript- , , ).
  • :. indexOf split , , : (, foo:blah:blah&bar:blah, foo is "blah:blah") — , ,
+1

, , , . :

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

function weirdStringToObject(str){
    var obj = {};
    str.split('&').forEach(function(substr){
        var kv = substr.split(':');
        var key = kv[0];
        var value = kv[1] || null;
        obj[key] = value;
    });
    return obj;
}

console.log(weirdStringToObject(keyAndValues));
Hide result

, .

+1

:

:

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

let result = str.split("&").reduce((r, s) => {
  let i = s.indexOf(':');
  r[s.slice(0, i)] = s.slice(i + 1);
  return r;
}, {});

console.log(result);
Hide result
+1

Source: https://habr.com/ru/post/1694142/


All Articles