根据另一个数组的键过滤数组

根据另一个数组的键过滤数组

本文介绍了根据另一个数组的键过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据另一个数组的键来过滤带有数据对象的数组.

I want to filter an array with data objects with it's keys based on another array.

我需要显示/隐藏基于以下数据的表的列:

I need to show/hide columns of a table, which is based on data like this:

var data = [{
    id: "1",
    name: "A",
    description: "number 1"
  },
  {
    id: "2",
    name: "B",
    description: "number 2"
  }
]

这将导致一个具有三列("ID",名称"和描述")和两行的表.

This results in a table with three columns ("ID", "Name" and "Description") and two rows.

我现在有一个下拉列表,其中包含每个表标题的一个复选框.

I now have a dropdown which contains one checkbox for each table header.

这些输入将存储在另一个数组中,因此当您在下拉列表中单击"id"时,该数组如下所示:

These inputs get stored in another array, so when you click "id" in the dropdown, the array looks like this:

var selectedColumns = ["id"]

..或当您选择"id"和"name"时:

..or when you select "id" and "name":

var selectedColumns = ["id","name"]

我现在想基于 selectedColumns 数组过滤我的 data 数组.

I now want to filter my data array based on the selectedColumns array.

我已经尝试过 filter 函数,但是我无法正确地思考如何做到这一点:

I already tried the filter function, but I can't wrap my head around on how to do it right:

   if (selectedColumns) {
    if (selectedColumns.length != 0) {
      data = data.filter(function(item) {
        var keys = Object.keys(item)
        keys.forEach(function(key) {
          if (!selectedColumns.includes(key)) {
            delete item[key];
          }
        })

        return true
      })
    }

背景:该表应该是可重复使用的Vue组件,因此所有键("id","name",..)和表头均会相应更改,从而防止对逻辑进行硬编码.

Background: This table should be a reusable Vue component, so all the keys ("id", "name", ..) and the table headers change accordingly, which prevents hardcoding the logic.

推荐答案

您可以获取所需键,并使用仅具有所需属性的新对象映射新数组.

You could take the wanted keys and map a new array with new objects with only the wanted properties.

function getProperties(array, keys) {
    return array.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));
}

var data = [{ id: "1", name: "A", description: "number 1" }, { id: "2", name: "B", description: "number 2" }];

console.log(getProperties(data, ['id', 'name']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用>> Object.fromEntries .

function getProperties(array, keys) {
    return array.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));
}

var data = [{ id: "1", name: "A", description: "number 1" }, { id: "2", name: "B", description: "number 2" }];

console.log(getProperties(data, ['id', 'name']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于根据另一个数组的键过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:31