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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With