按值过滤对象键并映射到数组

Vol*_*unz 8 javascript lodash

我正在创建一个有角度的应用程序,并且有带有复选框的项目。当用户单击复选框时,我会将选中的项目记录到对象中。该对象看起来像这样:

{1: false, 7: true, 8: true};
Run Code Online (Sandbox Code Playgroud)

When a user clicks on the delete button I need to get only selected items ids.

So I need to filter objects by values and as a result, get an array of integers.

I tried the following code with the lodash library:

console.log(_.pick(this.selectedItems, _.identity));

return _.pick(this.selectedItems, function (value, key) {
        return value;
      });
Run Code Online (Sandbox Code Playgroud)

But this returns an empty array.

What I need to get is an array [7,8]

What is wrong with my code?

Ori*_*ori 0

对于 lodash,您需要使用_.pickBy()而不是_.pick()因为_.pick()不接受回调。

这是一个生成的函数,_.flow()它将获取具有值的键true,并将它们转换为数字:

const { flow, partialRight: pr, pickBy, identity, keys, map } = _

const fn = flow(
  pickBy, // get the items by identity - this will remove keys with false values
  keys, // get the keys
  pr(map, Number) // map to numbers
);

const selectedItems = {1: false, 7: true, 8: true};

const result = fn(selectedItems);

console.log(result);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Run Code Online (Sandbox Code Playgroud)

还有 lodash/fp terser 版本:

const { flow, pickBy, identity, keys, map } = _

const fn = flow(
  pickBy(identity), // get the items by identity - this will remove keys with false values
  keys, // get the keys
  map(Number) // map to numbers
);

const selectedItems = {1: false, 7: true, 8: true};

const result = fn(selectedItems);

console.log(result);
Run Code Online (Sandbox Code Playgroud)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
Run Code Online (Sandbox Code Playgroud)