是否有一个lodash函数,或者可能是两个的组合,可以使一个对象和一组数组保持输出减少到这些键的对象?
{a: 1, b: 2, c: 3, d: 4} and ['a', 'c'] => {a: 1, c: 3}
答案 0 :(得分:3)
var obj = {a: 1, b: 2, c: 3, d: 4};
var keys = ['a', 'c'];
var filtered = _.pick(obj, keys);
document.body.innerHTML = '<pre>' + JSON.stringify(filtered, null, ' ') + '</pre>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
答案 1 :(得分:1)
你可以这样做。它不是lodash,但组装对象相当快。
function reduce(obj, keys)
{
var newObj = {};
keys.forEach(function(element)
{
newObj[element] = obj[element];
});
return newObj;
}
var myObj = {a: 1, b: 2, c: 3, d: 4};
var reducedObj = reduce(myObj, ["a", "c"]);