且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript,用下划线(或不)转换对象

更新时间:2021-12-15 05:25:59

您可以在 vanilla JS 中使用 mapreduceObject.keys 解决这个问题代码>:

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>

这是由:

  1. 获取外部对象的键并将每个键减少到该键上的 true 值集合.
  2. 在reduce中,我们:
  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. 仅过滤真实值
  2. 只返回每个值的键

该算法相当简单,几乎适用于您扔给它的任何对象.您可以轻松更改过滤器,并且可以尝试一些优化.

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.

下划线的等价物是:

    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>