【问题标题】:How to filter/reduce array of object with specific dynamically keys based in other array如何使用基于其他数组的特定动态键过滤/减少对象数组
【发布时间】:2020-07-29 13:33:00
【问题描述】:

我将解释我的问题。我没有时间考虑更多,而且我有一个阻止程序,我无法弄清楚,所以任何帮助将不胜感激。例如,我有一个对象数组(可以是包含 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 等.

【问题讨论】:

  • 请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。
  • 遍历数组是给定的,因此问题是从对象中删除不需要的键。您可以创建一个新对象并通过迭代keys 来设置它的属性,或者使用delete 将它们从现有对象中删除。前者意味着你要使用arr.map(),而后者是arr.forEach()的工作

标签: javascript arrays ecmascript-6 filter reduce


【解决方案1】:

您可以使用Array.prototype.map()reduce 来做到这一点。

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'];

const res = arr.map(item => keys.reduce((acc, key) => ({...acc, [key]: item[key]}), {}));

console.log(res);
.as-console-wrapper{min-height: 100% !important; top: 0;}

【讨论】:

  • 这正是我所需要的。非常感谢;)
  • 对不起,我没有检查它是否在数组中创建了更多对象,我需要一个对象中的所有内容。我必须更改对答案的接受,但您的答案仍然很好;)再次非常感谢您。
  • 很抱歉给您带来不便。我已经更新了我的代码。
  • 再次感谢,我喜欢 reduce + map 而不是 for 循环,所以我再次更改它:) 谢谢!!
  • 你是对的。所以如果你不介意我给了他最好的答案。
【解决方案2】:

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

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);

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 2018-10-20
    • 2021-11-21
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2021-02-19
    • 2021-03-21
    相关资源
    最近更新 更多