Let's say I have this javascript object
const recipe = {
name: 'Negroni',
ingredient1: 'Gin',
ingredient2: 'Campari',
ingredient3:'Vermouth',
preparation: 'Stir gin, vermouth, and Campari in an ice-filled mixing glass until very cold, about 30 seconds.'
}
I need a loop which will return string with each ingredient value, hence 'Gin', 'Campari', 'Vermouth'. How can I filter those values from this object?
I was trying to use for...in loop but I only accessed strings with propery names.
const recipe = {
name: 'Negroni',
ingredient1: 'Gin',
ingredient2: 'Campari',
ingredient3:'Vermouth',
preparation: 'Stir gin, vermouth, and Campari in an ice-filled mixing glass until very cold, about 30 seconds.'
}
for (const property in recipe) {
console.log(property.includes('ingredient') ? property : null);
}
You could get the value of the key by using the property indexer:
recipe[property]
const recipe = {
name: 'Negroni',
ingredient1: 'Gin',
ingredient2: 'Campari',
ingredient3:'Vermouth',
preparation: 'Stir gin, vermouth, and Campari in an ice-filled mixing glass until very cold, about 30 seconds.'
}
for (const property in recipe) {
console.log(property.includes('ingredient') ? recipe[property] : null);
}