Home > Net >  How to map this specific array of objects to the array grouped by the common key value
How to map this specific array of objects to the array grouped by the common key value

Time:11-20

I have this simplified array of objects

var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"},  {"function":"function_2","process":"process_3"},  {"function":"function_2","process":"process_4"}]

that I want to map in JS according to the keys into the following array:

result = [
{
    "function":"function_1",
    "process": [
      "process_1",
      "process_2" 
  ]
}, 
{
    "function":"function_2",
    "process": [
      "process_3",
      "process_4" 
  ]
}
]

CodePudding user response:

Dedicated to you my friend

var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"},  {"function":"function_2","process":"process_3"},  {"function":"function_2","process":"process_4"}]


var arr2 = items.reduce( (a,b) => {
  
    var i = a.findIndex( x => x.function === b.function);
  
    return i === -1 ? a.push({ function : b.function, process : [b.process] }) : a[i].process.push(b.process), a;
  
}, []);


console.log(arr2)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

var items = [{
  "function": "function_1",
  "process": "process_1"
}, {
  "function": "function_1",
  "process": "process_2"
}, {
  "function": "function_1",
  "process": "process_3"
}, {
  "function": "function_2",
  "process": "process_3"
}, {
  "function": "function_2",
  "process": "process_4"
}]

var uniqueFunctionList = [] // to keep track of unique function names
var resultArr = []          
items.forEach(item => {
  if (!uniqueFunctionList.includes(item.function)) { // item object doesnt exist
    uniqueFunctionList.push(item.function)           // add unique function name
    let tmp_obj = {}
    tmp_obj['function'] = item.function              // item is unique just push it
    tmp_obj['process'] = [item.process]              // make process array via []
    resultArr.push(tmp_obj)                          
  } else {                                           // function name is not unique
    resultArr.forEach(result => {                    // it is available in resultArr
      if (result.function == item.function) {        // find the function
        result.process.push(item.process)            // push to process array  
      }
    })
  }
})

console.log(resultArr)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related