Home > database >  JavaScript object array returned empty when filtering for value of a specific property
JavaScript object array returned empty when filtering for value of a specific property

Time:01-23

I'm trying to filter an array made up of objects with specific properties according to the value of a specific property, assuming all objects in the array have a property with this key.

MRE:

I'm trying to filter this array so that it returns an array only with objects whose name property includes a (sub-)string of second.

let arr = [
      {value:1,
      name: 'first'},
      {value:2,
      name:'second'},
    ];

    arr.filter((item) => {item.name.includes('second')});
    arr.filter((item) => {item.value === 1}); // this also doesn't work

Both of these last operations return an array of size zero.

Looking at a non-array counterpart:

    let obj = {value:1, name:'first'};
    obj.name.includes('first');
    obj.value === 1;

This returns true in both cases.

Why is that and how can I filter an array made up of objects according to their properties?

I tried filtering with single '' and double "" quotation marks (passing the string into the includes function), tried filtering a shallow and a deep copy, tried comparing the string properties with === (this should not work due to referencing anyways) etc. Both shallow and deep copy work as supposed, but filtering the original or any of the copies only returns empty arrays. Even if the callback function only returns true (so that any of the objects in the array should pass the test used for filtering), the returned array is still empty. I expect to receive arrays as explained in the MRE.

CodePudding user response:

The lambda (filter function) would throw an arrow because it contains curly brackets and does not contain the return keyword (so, it's not a function). The filter lambda should return a boolean. Remove the curly brackets and you're good. Or use [somearr].filter( v => { return [valueFiltered]; } )

const arr = [
  {value: 1, name: 'first'},
  {value: 2, name: 'second'}, ];

console.log(arr.filter( item => item.name.includes('second') ) );
console.log(arr.filter( item => item.value === 1 ) );
.as-console-wrapper {
    max-height: 100% !important;
}

CodePudding user response:

Try it:

let arr = [
      {value:1,
      name: 'first'},
      {value:2,
      name:'second'},
    ];

   arr.filter((item) => {return item.name.includes('second')});
   arr.filter((item) => {return item.value === 1})
  • Related