更新时间:2021-12-15 05:25:59
您可以在 vanilla JS 中使用 map
、reduce
和 Object.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>
这是由:
true
值集合.true
values on that key.该算法相当简单,几乎适用于您扔给它的任何对象.您可以轻松更改过滤器,并且可以尝试一些优化.
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>