-2

i am unable to find particular object in js if i use .find() any other way can i do the same or can i do the same using .includes()

  const inventory = [
              {name: 'owner_hall_light', id: 2},
              {name: 'owner_kitchen_ac', id: 0},
              {name: 'owner_bed_fan', id: 5}
            ];
            
            const result = inventory.find( ({ name }) => name === 'kitchen' );
            //expected output
            console.log(result) //   {name: 'owner_kitchen_ac', id: 0}

// i am getting output as undefined
jeena
  • 33
  • 4
  • 1
    None of the items _has_ a `name` that is strict _equal_ to `'kitchen'`, so _of course_ you are not getting a result here. Go research how to find out if one string _contains_ another in JS. – CBroe Jul 28 '21 at 10:26
  • You can use regular expressions in your find function. – SimpleProgrammer Jul 28 '21 at 10:26
  • You might want to use name.includes("kitchen") instead of name === "kitchen" – MrJami Jul 28 '21 at 10:28

3 Answers3

0

name === 'kitchen' evidently will not be found. Test the name for the occurance of 'kitchen':

const inventory = [{
    name: 'owner_hall_light',
    id: 2
  },
  {
    name: 'owner_kitchen_ac',
    id: 0
  },
  {
    name: 'owner_bed_fan',
    id: 5
  }
];

const result = inventory.find(({ name }) => /kitchen/i.test(name));
//                                          ^ test using regexp
console.log(result);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • can i use a variable instead of kitchen directly for ex: let find ='kitchen' and call variable find inplace of kitchen – jeena Jul 28 '21 at 10:36
0

Try this answer.

var inventory = [
    {name: 'owner_hall_light', id: 2},
    {name: 'owner_kitchen_ac', id: 0},
    {name: 'owner_bed_fan', id: 5}
  ];
  
  const result1 = inventory.find( x => x.name.includes("kitchen"));
  //expected output
  console.log(result1) //   {name: 'owner_kitchen_ac', id: 0}
Selva Mary
  • 658
  • 1
  • 4
  • 17
0

If you want to use a string to test against use something like name.includes(word). I've created a function here that accepts the inventory, and a word, and returns an object.

const inventory=[{name:"owner_hall_light",id:2},{name:"owner_kitchen_ac",id:0},{name:"owner_bed_fan",id:5}];

function findObject(inventory, word) {
  return inventory.find(({ name }) => name.includes(word));
}

const word = 'kitchen';
console.log(findObject(inventory, word));

const word2 = 'bed';
console.log(findObject(inventory, word2));

const word3 = 'koala';
console.log(findObject(inventory, word3));
Andy
  • 61,948
  • 13
  • 68
  • 95