Search code examples
javascriptarraysecmascript-6javascript-objectsecmascript-5

Avoid string "null" using split method of javascript


I am trying to parse a string with a following format

"value1=name1:value2=test1,value1=name2:value2=null,value1=null:value2=test3"

I would want this to be parsed as

[{ value1: "name1", value2: "test1"}, { value1: "name2", value2: "NA"},{ value1: "NA", value2: "test3"}]

If in case any value post splititng is null , just make is "NA". Since I am using split the null value is being coerced to string. Hence setting "NA" using nullish coalescing(??) is not working and hence it still returns null and not NA. It would also be helpful , If any body can suggest a simpler way to achieve this

Code that I have tried.

let input = "value1=name1:value2=test1,value1=name2:value2=null,value1=null:value2=test3";
let items = input.split(",");
let pairs = items.map((item) => {
  let splitItems = item.split(":");
  let value1 = splitItems[0].split("=")?? "NA";;
  let value2 = splitItems[1].split("=") ?? "NA";
  return { value1, value2 };
});

Solution

  • You could use the ternary operator

    const str =
      "value1=name1:value2=test1,value1=name2:value2=test2,value1=null:value2=test3"
    
    const res = str.split(",").map((el) =>
      el.split(":").reduce((acc, pair) => {
        const [key, value = "NA"] = pair.split("=")
        return {
          ...acc,
          [key]: value === "null" ? "NA" : value,
        }
      }, {})
    )
    
    console.log(res)