Friday, October 28, 2022

[FIXED] How to group by a nested parameter

Issue

How could I improve this code to doesn't use so many _.each and by doesn't always verifying the object emptyness of its properties

  _.each(initial_obj, function(value, key){
    _.each(value, function(value2, key2){
      _.each(value2, function(value3, key3){
        _.isEmpty(new_obj[key3]) && (new_obj[key3] = {});
        _.isEmpty(new_obj[key3][key]) && (new_obj[key3][key] = []);
        new_obj[key3][key][key2] = value3;
      })
    })
  })


old_obj: {'a': {'en', 'es', 'pt'}, 'b': {'en', 'es', 'pt'}, 'c': {'en', 'es', 'pt'}})

  new_obj: {'en': ['a': [], 'b': [], 'c': []},
                          'es': {'a': [], 'b': [], 'c': []},
                          'pt': {'a': [], 'b': [], 'c': []}
                          })

Solution

Iterate the keys of the object using Object#keys and Array#reduce. Then iterate the inner array, with Array#forEach. For each string in the array, assign the key with an empty array:

const obj = {'a': ['en', 'es', 'pt'], 'b': ['en', 'es', 'pt'], 'c': ['en', 'es', 'pt']};

const result = Object.keys(obj).reduce((r, key) => {
  obj[key].forEach((str) => r[str] = Object.assign(r[str] || {}, { [key]: [] }));
  
  return r;
}, {});

console.log(result);



Answered By - Ori Drori
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.