Ошибка типа: obj [ключ] .include не является функцией: в функции фильтра - PullRequest
0 голосов
/ 06 мая 2019

Я хотел бы найти объекты, которые имеют какую-либо собственность с некоторым значением.Но у меня есть ошибка: TypeError: obj [key] .include не является функцией.Как это исправить?

var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];

function filterIt(arr, searchKey) {
  return arr.filter(function(obj) {
    return Object.keys(obj).some(function(key) {
      return obj[key].includes(searchKey);
    })
  });
}

filterIt(aa, 'txt');

Ответы [ 2 ]

1 голос
/ 06 мая 2019

Попробуйте использовать Object.values вместо:

var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];

function filterIt(arr, searchKey) {
  return arr.filter(function(obj) {
    return Object.values(obj).includes(searchKey);
  });
}

console.log(filterIt(aa, 'txt'));
.as-console-wrapper { max-height: 100% !important; top: auto; }

Вы также можете сделать этот код более компактным:

var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];

const filterIt = (arr, searchKey) => arr.filter(obj => Object.values(obj).includes(searchKey));

console.log(filterIt(aa, 'txt'));
.as-console-wrapper { max-height: 100% !important; top: auto; }
0 голосов
/ 06 мая 2019

Возьмите Object.values объекта, чтобы получить массив значений, и затем вы сможете увидеть, соответствуют ли какие-либо значения searchKey (хотя вы ищете значения , так что, вероятно, лучшеназвать его valueToFind):

var aa = [{
    id: 1,
    type: 1,
    status: 1,
    name: 'txt'
  },
  {
    id: 2,
    type: 1,
    status: 1,
    name: 'txt',
  },
  {
    id: 3,
    type: 0,
    status: 0,
    name: 'txt'
  },
  {
    id: 4,
    type: 0,
    status: 0,
    name: 'wrongname'
  },
];

function filterIt(arr, valueToFind) {
  return arr.filter(function(obj) {
    return Object.values(obj).includes(valueToFind);
  });
}

console.log(filterIt(aa, 'txt'));

Поскольку вы использовали .some, рассмотрите возможность использования синтаксиса ES6 для более краткого кода:

var aa = [{
    id: 1,
    type: 1,
    status: 1,
    name: 'txt'
  },
  {
    id: 2,
    type: 1,
    status: 1,
    name: 'txt',
  },
  {
    id: 3,
    type: 0,
    status: 0,
    name: 'txt'
  },
  {
    id: 4,
    type: 0,
    status: 0,
    name: 'wrongname'
  },
];

const filterIt = (arr, valueToFind) => arr.filter(
  obj => Object.values(obj).includes(valueToFind)
);

console.log(filterIt(aa, 'txt'));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...