javascript - 如何使用基于其他数组的特定动态键来过滤/减少对象数组

标签 javascript arrays ecmascript-6 filter reduce

我要解释一下我的问题。我没有时间更多地考虑这个问题,而且我有一个拦截器,我无法弄清楚,所以任何帮助将不胜感激。例如,我有一个对象数组(可以是包含 100 多个元素的数组):

  const arr = [
    { value: '1', id: 1, number: 1, other: 'example', data: '6' },
    { value: '2', id: 2, number: 2, other: 'example', data: '7' },
    { value: '3', id: 3, number: 3, other: 'example', data: '8' },
    { value: '4', id: 4, number: 4, other: 'example', data: '9' },
    { value: '5', id: 5, number: 4, other: 'example', data: '10' },
  ];

在另一个数组中,我有包含特定键的字符串:

  const keys = ['value', 'id', 'number'];

我的问题是我想返回变量arr仅包含基于keys变量上的值的对象。类似这样的事情:

 const arr = [
    { value: '1', id: 1, number: 1 },
    { value: '2', id: 2, number: 2 },
    { value: '3', id: 3, number: 3 },
    { value: '4', id: 4, number: 4 },
    { value: '5', id: 5, number: 4 },
  ];

我希望动态地拥有它,因为 keys 变量中的值不是常量,可以是 valueotherdata 或仅 dataidother

最佳答案

创建一个函数,该函数将根据键数组返回并使用该函数进行映射..

const arr = [
        { value: '1', id: 1, number: 1, other: 'example', data: '6' },
        { value: '2', id: 2, number: 2, other: 'example', data: '7' },
        { value: '3', id: 3, number: 3, other: 'example', data: '8' },
        { value: '4', id: 4, number: 4, other: 'example', data: '9' },
        { value: '5', id: 5, number: 4, other: 'example', data: '10' },
      ];

    const keys = ['value', 'id', 'number'];

    function pick(obj, keys){
        let result = {};
        for(let i=0; i<keys.length; i++){
            result[keys[i]] = obj[keys[i]];
        }
        return result;
    }

    let finalArr = arr.map( value => pick(value,keys));

    console.log(finalArr);

关于javascript - 如何使用基于其他数组的特定动态键来过滤/减少对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61248073/

相关文章:

javascript - 网页不会自动调整到任何屏幕高度

javascript - 应用程序模块不可用、拼写错误或忘记加载 - 在 grunt 构建之后

javascript - 如何更改默认音频输入

javascript - Traceur 运行时 : Super expression must either be null or a function, 未定义

javascript - 使用 vm.runInNewContext 创建类(在 ES6 中强制类表达式而不是类声明)

javascript - 防止在 TinyMCE 中输入默认键盘事件

javascript - 函数构造函数 - 使用原型(prototype)添加函数给出 - 未捕获的语法错误 : Unexpected token {

javascript - 你如何引用 Array.prototype.slice.call()?

arrays - 如何使用where子句检查postgres数组中是否存在值

javascript - 在 ES6/ES7 中有这个的简写吗?