Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return value(object) form filter method on Object.keys() instead of key?

const notes = {
  'jk2334|notes-md-23': {
    id: 'notes-md-23',
    text: 'First Note'
  },
  'jk2334|notes-xd-34': {
    id: 'notes-xd-34',
    text: 'Second Note'
   },
   'fd4345|notes-mf-54': {
    id: 'notes-mf-54',
    text: 'Third Note'
   }
}

const result = Object.keys(notes).filter(note => {
        if(note.startsWith('jk2334')) {
            console.log('from inner -', notes[note]);
            return notes[note];
        }
    })

console.log(result)

If I run this code it returns only key but not the value of the object. But if I console inside the condition it returns the value.

I want to return the array of value not key. What should I do now?

like image 710
Md Muaz Ahmed Avatar asked Jan 26 '26 03:01

Md Muaz Ahmed


1 Answers

The callback to Array#filter is expected to return a boolean value. true if you want to keep the value and false if you don't. You cannot use it to convert input values to different output values. The code you have works accidentally because objects are truthy values.

To convert input to output values you can call Array#map after filtering to map the keys back to values:

const notes = {
  'jk2334|notes-md-23': {
    id: 'notes-md-23',
    text: 'First Note'
  },
  'jk2334|notes-xd-34': {
    id: 'notes-xd-34',
    text: 'Second Note'
   },
   'fd4345|notes-mf-54': {
    id: 'notes-mf-54',
    text: 'Third Note'
   }
}

const result = Object.keys(notes)
  .filter(note =>  note.startsWith('jk2334'))
  .map(key => notes[key])

console.log(result)
like image 116
Felix Kling Avatar answered Jan 28 '26 17:01

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!