通过对象键过滤对象数组

时间:2018-07-13 09:02:41

标签: javascript arrays

如何通过键过滤对象数组?

const users = [{
  forename: "Arlene",
  isActive: true,
  isManager: false,
  language: "fr",
  partnerNumber: "92250507",
}, {
  ...
}]

应按键数组过滤

const keys = ['forename', 'isActive'];

预期结果是:

const filteredUsers = [{
  forename: "Arlene",
  isActive: true,

}, {
  ...
}, {
  ...
}]

谢谢!

4 个答案:

答案 0 :(得分:0)

您可以像以下一样使用mapmap()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

const users = [{
    forename: "Arlene",
    isActive: true,
    isManager: false,
    language: "fr",
    partnerNumber: "92252107",
  },
  {
    forename: "Chris",
    isActive: false,
    isManager: false,
    language: "en",
    partnerNumber: "92250507",
  }
]

let filteredList = users.map(item => {
  return {
    forename: item.forename,
    isActive: item.isActive
  }
});

console.log(filteredList)

答案 1 :(得分:0)

尝试这样的事情。

const users = [{
  forename: "Arlene",
  isActive: true,
  isManager: false,
  language: "fr",
  partnerNumber: "92250507",
}, {
  forename: "Arlene2",
  isActive: true,
  isManager: false,
  language: "fr",
  partnerNumber: "92250507",
}]

const keys = ["forename", "isActive"];

const filteredUsers = users.map(user => {
  let u = {};
  keys.forEach(key => {
    u[key] = user[key];
  });
  return u;
});

console.log(filteredUsers);

答案 2 :(得分:0)

您提出问题的方式似乎只是想map,就像将数组元素更改为其他格式一样。

如果您想filter仅获得活动的(isActive?),那么您也应该使用filter

我假设您的密钥只是硬编码的,所以实际上并不需要它。有了这个,我们就可以创建我们的mapper函数并使用一些解构来简化操作

const users = [{
    forename: "Arlene",
    isActive: true,
    isManager: false,
    language: "fr",
    partnerNumber: "92252107",
  },
  {
    forename: "Chris",
    isActive: false,
    isManager: false,
    language: "en",
    partnerNumber: "92250507",
  }
]

const mapUser = ({ forename, isActive }) => ({ forename, isActive });
let filteredList = users.map(mapUser);

console.log(filteredList)

答案 3 :(得分:-2)

@Paul给出了很好的答案..您也可以使用“过滤器”数组帮助器..而不是像这样的地图帮助。

  const users = [{
  forename: "Arlene",
  isActive: true,
  isManager: false,
  language: "fr",
  partnerNumber: "92250507",
}, {
  forename: "Arlene2",
  isActive: true,
  isManager: false,
  language: "fr",
  partnerNumber: "92250507",
}]

var filteredList = users.filter(function(user) {
    return {forename: user.forename, isActive: true};
});
filteredList;