PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to group by a nested parameter

 October 28, 2022     each, is-empty, javascript, ruby     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing