Javascript, Transforming object with underscore (or not)

后端 未结 2 567
野的像风
野的像风 2021-01-22 15:19

I am looking to prepare an object for send. It initially looks like so :

var myObj = {\"state\":{\"Saved\":true,\"Committed\":false,\"Published\":false},\"discip         


        
相关标签:
2条回答
  • 2021-01-22 15:46

    You can solve this in vanilla JS using map, reduce, and Object.keys:

    var myObj = {
      "state": {
        "Saved": true,
        "Committed": false,
        "Published": false
      },
      "discipline": {
        "Marketing": true
      }
    };
    
    var output = Object.keys(myObj).reduce(function(p, collection) {
      var values = myObj[collection];
      p[collection] = Object.keys(values).filter(function(key) {
        return values[key] === true;
      });
      return p;
    }, {});
    
    document.getElementById('results').textContent = JSON.stringify(output);
    <pre id="results"></pre>

    This works by:

    1. Taking the keys of the outer object and reducing each to a collection of true values on that key.
    2. In the reduce, we:
      1. Filter only true values
      2. Return only the key for each value

    The algorithm is fairly simple and should work with almost any object you throw at it. You can change the filter easily and there may be a few optimizations you could try out.

    The equivalent with underscore would be:

        var myObj = {
          "state": {
            "Committed": false,
            "Saved": true,
            "Published": false
          },
          "discipline": {
            "Marketing": true
          }
        };
    
        var output = _.reduce(myObj, function(p, values, collection) {
          p[collection] = _.chain(values).map(function(value, key) {
            console.log('filter', arguments);
            if (value === true) {
              return key;
            }
          }).filter(function(it) {
            return !!it;
          }).value();
          return p;
        }, {});
    
        document.getElementById('results').textContent = JSON.stringify(output);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <pre id="results"></pre>

    0 讨论(0)
  • 2021-01-22 16:01

    You were nearly there with your answer. Use _.mapObject to retain the keys instead of map.

        var result = _.mapObject(myObj, function(value){
            return _.keys(_.pick(value, Boolean));
        });
    
    0 讨论(0)
提交回复
热议问题