Home > Software design >  Split string and merge into dictionary in map
Split string and merge into dictionary in map

Time:12-21

I am building a simple react app and I am trying to convert string and integer into dict in map function.

I have strings like

first string-100, second string-300, third string-500

and then after splitting the comma then It will become like

var array = ['first string-100', 'second string-300', 'third string-500']

I am using .map() like

array.map((res) => {
    // splitting the "-"
    res.split("-").map((value) => {
      // first string
      // 100

      // second string
      // 300

      I am trying to create it like [{"key": "first string", "integer": 100}, {"key": "second string", "integer": 300}]
      

    })
})

I have no idea how can I convert it like it in the dict and list.

I have also tried using

array.map((res) => {
    // splitting the "-"
    res.split("-").map((value) => {
      // first string
      // 100

      // second string
      // 300

      var newDict = {"key" : "", "integer": 0}
      if (isNaN(parseInt(keyValue)) {
          newDict = {"key": keyValue}
      } else {
          newDict = {"integer": keyValue}
      }
      

    })
})

But It gave me results like

{"key" : "first string"}
{"integer" : 100}

{"key" : "second tring"}
{"integer" : 300}

And I want like

[{"key": "first string", "integer": 100}, {"key": "second string", "integer": 300}]

I want them merged "key" and "integer" in one dict and all in list.

Any help would be much Appreciated

CodePudding user response:

You can use map

const raw = 'first string-100, second string-300, third string-500'

const arr = raw.split(", ")

const result = arr.map((value) => {
  const [key, integer] = value.split('-')

  return {
    key,
    integer: parseInt(integer, 10),
  }
})

console.log(result)

CodePudding user response:

This should work.

string.split(",").map(x => {
const parts = x.split("-");
return { key: parts[0], integer: parseInt(parts[1]) }
});

CodePudding user response:

One approach is as follows, with explanatory comments in the code:

// the initial String:
const start = "first string-100, second string-300, third string-500",
  // here we use Object.fromEntries() to create a new Object from the
  // resulting nested Array:
  obj = Object.fromEntries(
          // using String.prototype.split() to split the initial String
          start.split(
            // this regular expression matches zero-or-more (*) white-space
            // characters (\s) followed by a comma (,) followed by zero-
            // or more white-space characters:
            /\s*,\s*/
          // the resulting Array is then passed to Array.prototype.map():
          ).map(
            // we use the anonymous Arrow function to pass the Array-element,
            // the current String of the Array of Strings, into the
            // function body.
            // in the function body we then split the String into
            // a two-part Array, which will be returned to Object.fromEntries
            // as key-value pairs:
            (str) => str.split('-')
          )
        );


console.log(obj);
/*
  {
    "first string": "100",
    "second string": "300",
    "third string": "500"
  }
*/

JS Fiddle demo.

References:

  • Related