首页 > 解决方案 > 在对象数组中查找属性(作为字符串存储在变量中)

问题描述

我有一个存储不同“学生”数据的对象数组。

var pupils = [
{
    id: 0,
    name: 'will'
},
{
    id: 1,
    name: 'megan'
}
];

我想创建一个名为“findPupil”的函数,它接受三个参数:您知道的属性、您知道的值以及您要查找的属性。

假设您知道要查找的学生的 id 为 1,但您不知道他们的名字。在这种情况下,您可以像这样调用函数:

var name = findPupil('id', 1, 'name'); // should now store 'Megan' as a string

这是我写的函数:

function findPupil(property, value, find) {
pupils.forEach(function(pupil) {
    if(pupils[pupil][`${property}`] === value) {
      return pupils[pupil][`${find}`];
    }
  });
}

调用此函数将返回以下内容:

Error: Cannot read property 'id' of undefined

如何使此功能起作用?

标签: javascriptarraysforeachjavascript-objects

解决方案


用于Array.find()查找具有您知道的属性的对象,或者如果未找到对象则使用默认值。从对象中提取find属性:

const pupils = [{"id":0,"name":"will"},{"id":1,"name":"megan"}];

const findPupil = (property, value, find) =>
  (pupils.find(o => o[property] === value) || {})[find];

const name = findPupil('id', 1, 'name');

console.log(name);


推荐阅读