Returning an element within an object by value

Hello

I am trying to get my head around the syntax required to return an element within an object by the value associated with a key in Javascript. For instance, referring to the meal-maker exercise
(https://www.codecademy.com/courses/introduction-to-javascript/projects/meal-maker), how would I call the details of a dish? If I had an appetizer called ‘Gloop’, how could I get all of the properties associated with this dish with a specified reference to ‘Gloop’?

Something like:

console.log(menu._courses.appetizers.dish [‘Gloop’])

I hope this question makes sense…

I have found quite complicated functions to do the job, but am looking for some nice simple syntax to be able to use.

Many thanks!

Object basics…

object = {
    name: "Wee Gillis",
    age: 19,
    home: "St. William, Scotland"
}

name, age and home are keys, and the data are values. We refer to them as key-value pairs.

Keys are data type string, so when written as subscripts must appear in quotes.

console.log(obect['name'])    // Wee Gillis

We can represent a literal key with a variable…

variable = "name"

and when writing in the subscript the variable will behave the same way the string literal does.

console.log(object[variable])    // Wee Gillis

Notice there are no quotes since the variable represents a string, but is not a string literal, per se.

When we write keys that exist in an object, they can be written with dot notation…

console.log(object.name)    // Wee Gillis

We cannot write,

console.log(object.variable)

since there is no defined key, variable.

In your example,

console.log(menu._courses.appetizers.dish [‘Gloop’])

we see dish but appetizers is an array of objects.

console.log(menu._courses.appetizers[index])

Thank you for your quick reply!

If I know the key-value pair, how could I pull that element out of an object array? (I am not sure if my syntax is correct in describing this problem…)

I found this on the great googler:

const books = {
‘978-0099540946’:{
isbn: ‘978-0099540946’,
author: ‘Mikhail Bulgakov’,
title: ‘Master and Margarita’
},
‘978-0596517748’: {
isbn: ‘978-0596517748’,
author: ‘Douglas Crockford’,
title: ‘JavaScript: The Good Parts’
},
‘978-1593275846’: {
isbn: ‘978-1593275846’,
author: ‘Marijn Haverbeke’,
title: ‘Eloquent JavaScript’
}};

function getBookByIsbn(isbn, books){
return books[isbn];
}

const myBook = getBookByIsbn(‘978-1593275846’, books);

console.log(myBook)

<<<***>>>

it does what I would like, but is a lot of code for a simple request. Is there a way to bypass the function?

1 Like
console.log(books['978-1593275846'])

Ahaha! I see… I was being daft. The ISBN is the key to the element in the object (is this the right way of saying this?), as well as a value within the element paired with the key ‘isbn’.

Thank you.

So to find a value within an object element (I am sure this is not the right way to say this…), is it necessary to iterate over the elements associated with a key?

A similar data structure for the menu exercise would be:

const menu = {
courses: {
appetizers : {
gloop: {
dish: ‘Gloop’,
price: 10,
},
grout: {
dish: ‘Grout’,
price: 15,
},
},
mains : {
truggles: {
dish: ‘Truggles’,
price: 20
},
gizzlings: {
dish: ‘Gizzlings’,
price: 20,
},
},
desserts : {
kippins: {
dish: ‘Kippins’,
price: 10
},
lillipoops: {
dish: ‘Lillipoops’,
price: 15
},
},
},
}

console.log(menu.courses.appetizers.grout)

element is the common term to refer to an array item.

item is the common term to refer to a key-value pair.

menu.courses.appetizers.gloop.dish

Ok. Thank you very much. I think this has helped me clear up a lot of confusion.

Just to be clear, if I had a long list of items in an object which contained people’s information and I wanted to use one value to find another value within that list, would I need to iterate through the items, match the value I entered and then use the index of the matched item to extract the other value?

1 Like

If you have two lists of equal length and they correspond with each other then yes, iterate one list to find the term, and use its index to access the other list for the corresponding element.

Ok. I am going to try to build a function that can search a specified key within an object for a value and return another value from another specified key… I am getting tied in knots. I am sure there must be a simple way! I will leave it for tonight though.

Something like:

const menu = {
courses: {
appetizers : [ {dish: ‘Gloop’, price: 10}, {dish: ‘Grout’, price: 15} ],
mains : [ {dish: ‘Truggles’, price: 20}, {dish: ‘Gizzlings’, price: 20} ],
desserts: [ {dish: ‘Kippins’, price: 10}, {dish: ‘Lillipoops’, price: 15} ],
},
}

function searchInReturnOut (searchValue, object, parentKey, searchKey, returnKey) {
//something in here
}

console.log(searchInReturnOut(“Gloop”, menu, courses.appetizers, name, price))

Thanks again for your help!

I’ll have to come back to this later; just had some company arrive.

Is something like this what you are attempting to do?

const menu = {
courses: {
appetizers : [ {dish: 'Gloop', price: 10}, {dish: 'Grout', price: 15} ],
mains : [ {dish: 'Truggles', price: 20}, {dish: 'Gizzlings', price: 20} ],
desserts: [ {dish: 'Kippins', price: 10}, {dish: 'Lillipoops', price: 15} ],
}
}
//Uses .find() to search the array. Returns the object (d) where the dish property matches then returns the price of that object.
console.log(`The price of Gizzlings is $${menu.courses.mains.find(d => d.dish == 'Gizzlings').price} per plate.`)

Output:

The price of Gizzlings is $20 per plate.

1 Like

Nice job. I was a long ways off introducing that iterator but we would have got there, eventually.

1 Like

:sob:

This is a function

d => d.dish == 'Gizzlings'

You can call it by itself to experiment with how it works

let p = d => d.dish == 'Gizzlings'
console.log(p({dish: 'Gizzlings'}))
console.log(p({dish: 'GizzIings'}))

And then you’ll need to consider what Array.find does with the function that is given to it as an argument

Ah! Yes! Thank you. That’s perfect.

Now to try to figure out how it works… can’t quite work out what the .price is doing on the end. Guess just learn it for now and hope it makes sense later!

Thank you both.

The function I get, I think. It is the .price that is bamboozling me.

It seems to be returning a value from outside the function.

That’s key lookup for an object

object.key

The concept of return does not in any way make sense outside a function since it has to do with producing an output for a function.

You can in some sense say that an expression returns something, but then you are talking about evaluation, same as how 1 + 1 evaluates to 2

Similarly, the object in object.key can be any arbitrary expression that evaluates to an object
(some expression evaluating to an object).key

Ahhhhh… Yeah… ok… Thank you… I think I am getting it.

menu.courses.mains[//.find function evaluating (or refining) object definition\].price

Ok… just to be really annoying… How can I replace the hardcoded keyAddress with variables?

const add1 = ‘menu’
const add2 = ‘courses’
const add3 = ‘mains’

console.log([add1][add2][add3].find(d => d.dish === ‘Gizzlings’).price)

// or:

const add = ‘menu.courses.mains’

console.log([add].find(d => d.dish === ‘Gizzlings’).price)

Your code already does that if you look at it

If you mean multiple keys then … that’s multiple lookups
If you want to store multiple things then that’s the kind of thing you’d use an array for. And if you then wanted to use those multiple things, that’s what loops are for.

Alternatively if you wanted to use only a single lookup then use a data structure that isn’t nested.

The problem you’re imagining where you’d want multiple lookups as one key is probably instead solved by sending in the relevant part instead of some outer-most global object along with a long list of keys to get to where the relevant data is. Or holding on to something with a variable.