Search code examples
javascriptarraysobjectreduce

Combine object with key values matching to pattern


I am trying to split the object based on the keys starting with a pattern like S.1.1.0.

const obj = {
  "S.1.1.0": "Hi",
  "S.1.1.1": "what is your name",
  "S.1.1.2": "Can we meet",
  "S.2.1.1": "what is the time now",
  "S.2.1.2a": "It is 6 PM",
  "S.3.1.1b": "where do you live",
  "S.3.1.2": "how is the weather",
  "S.3.1.3": "it is very cold",
  "S.3.1.3b": "yes",
}

const result = Object.entries(obj).reduce((a, [key, val]) => { 
  const [s, k, v] = key.split('.')  
  const item = a.find(({
    key: itemkey
  }) => itemkey === k)  
 console.log(item)
  if (item) {  
    item[v] = val
  } else {  
    a.push({
      key: k,
      [v]: val
    })
  }

  return a
}, [])

console.log(result)

Expecting the output to be like where key value starting with S.1 combined together. The key value is dynamic by always starts like S.1, S.2 ...

 [{
        "S.1.1.0": "Hi",
        "S.1.1.1": "what is your name",
        "S.1.1.2": "Can we meet"
      },
      {
        "S.2.1.1": "what is the time now",
        "S.2.1.2a": "It is 6 PM"
      },
      {
        "S.3.1.1b": "where do you live",
        "S.3.1.2": "how is the weather",
        "S.3.1.3": "it is very cold",
        "S.3.1.3b": "yes"
      }
    ]

Solution

  • You could reduce() to an object with the mapping key as index.

    Then use Object.values(result) to get the desired result

    const obj = {
      "S.1.1.0": "Hi",
      "S.1.1.1": "what is your name",
      "S.1.1.2": "Can we meet",
      "S.2.1.1": "what is the time now",
      "S.2.1.2a": "It is 6 PM",
      "S.3.1.1b": "where do you live",
      "S.3.1.2": "how is the weather",
      "S.3.1.3": "it is very cold",
      "S.3.1.3b": "yes",
    }
    
    const result = Object.entries(obj).reduce((a, [key, val]) => { 
      const mapping = key.split('.', 2).join('.');
      
      if (!a[mapping]) a[mapping] = { };
      a[mapping][key] = val;
      
      return a;
    }, {})
    
    const resultArray = Object.values(result);
    
    console.log(resultArray)

    Output:

    [
      {
        "S.1.1.0": "Hi",
        "S.1.1.1": "what is your name",
        "S.1.1.2": "Can we meet"
      },
      {
        "S.2.1.1": "what is the time now",
        "S.2.1.2a": "It is 6 PM"
      },
      {
        "S.3.1.1b": "where do you live",
        "S.3.1.2": "how is the weather",
        "S.3.1.3": "it is very cold",
        "S.3.1.3b": "yes"
      }
    ]