How do I use filter on an object?

  • 0
    I want to do an inaccurate search on an object and get back the keys of the objects that are being verified.
    var word = $(this).val() // == 'val'
    
    var my_obj =	{
    		'1':{'text':'val-1'},
    		'2':{'text':'val-2'},
    		'3':{'text':'val-3'}
    	};
    
    
    const m = my_obj.filter(function (e) {
    		if (e.text.indexOf(word) != -1 ){
    		  return key;
    		}
    });
    console.log(m);

    How can I do this?
    I cannot change the object itself.
    JavaScript Anonymous, Aug 24, 2020

  • 3 Answers
  • 0
    this property only exists in the prototype of arrays, there is an option for you

    Object.values(my_obj).filter( e => e.text.indexOf(word) != -1)


    the output is an array with the required objects
    Anonymous

  • 0
    No, this is an array method. Convert your object to an array [... Object.values ​​(my_obj)]
    Anonymous

  • 0
    Object.keys (my_obj) .filter ((el, id) = & gt; my_obj [el] .text === 'val-2')
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!