Am I utilizing hasOwnProperty() correctly here

Tell us what’s happening:
Describe your issue in detail here.
My plan is to loop through collection array and use hasOwnProperty on each element to determine if it matches the one in source array.

I’m very underconfident working with object arrays and so the ground is always shifty for me. I think I’m using hasOwnProperty() correctly and I think my logic is good…but I have a strong feeling that I’m missing something.

Can someone help?

Thank you,
Nick

  **Your code so far**

function whatIsInAName(collection, source) {
const arr = [];
//  Loop through collection array and test if each element matches the element within source array
for(let i = 0; i < collection.length; i++){
if(collection[i].hasOwnProperty(source)){
//if element returns true, push that element to arr array
  arr.push(collection[i])
} console.log(arr)
}
// Only change code above this line
return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36

Challenge: Wherefore art thou

Link to the challenge:

No, you are not, as source as an object, not a string

1 Like
// Only change code below this line

I’m stuck with Object.values()…I’m trying to get the values from the collection array but when I console.log the array I (supposedly) pushed it into, nothing’s there. I did something similar with Object.keys(). I don’t understand why the array is empty. What am I misinterpreting about the data that would cause it to be such?
Thanks,
Nick

/*

Get an array of the keys from the `source`

Get an array of the values from the `source`

*/

let srcKeys = Object.keys(source);

let srcVals = Object.values(source);

console.log(srcKeys)

console.log(srcVals)

/*

Loop through all items in the `collection`

    Get an array of the keys from the current item

    Get an array of the values from the current item

*/

let keyCurr = [];

let valCurr = []

for(let i = 0; i < collection.length; i++){

         keyCurr.push(Object.keys(collection[i]))

   console.log(keyCurr)

    for(let j = 0; j < collection[i].length; j++){

     valCurr.push(Object.values(collection[i][j]));

     

    } 

}

/*    If every source key is present in the current item's keys 

    and every source value is present in the current item's values

        Add the item to the return array

Return the array*/

  // Only change code above this line

  return arr;

}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

When you ask for help please post your whole code - where is the function call?

Giving pieces makes hard to debug

function whatIsInAName(collection, source) {

  const arr = [];

  // Only change code below this line

/*

Get an array of the keys from the `source`

Get an array of the values from the `source`

*/

let srcKeys = Object.keys(source);

let srcVals = Object.values(source);

console.log(srcKeys)

console.log(srcVals)

/*

Loop through all items in the `collection`

    Get an array of the keys from the current item

    Get an array of the values from the current item

*/

let keyCurr = [];

let valCurr = []

for(let i = 0; i < collection.length; i++){

         keyCurr.push(Object.keys(collection[i]))

   console.log(keyCurr)

    for(let j = 0; j < collection[i].length; j++){

     valCurr.push(Object.values(collection[i][j]));

     

    } 

}

/*    If every source key is present in the current item's keys 

    and every source value is present in the current item's values

        Add the item to the return array

Return the array*/

  // Only change code above this line

  return arr;

}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

Latest attempt. I’m really stuck on creating an array of the keys and values to check against source. It seems that the value of collection is both the “first” and “last” title along with the ‘value’ of “first” and “last” name. I don’t know how to decouple these so that I can compare them to the key value pair in source. My latest attempt is below. Where am I going wrong?

function whatIsInAName(collection, source) {

  const arr = [];

  // Only change code below this line

/*

Get an array of the keys from the `source`

Get an array of the values from the `source`

*/

let keySrc = Object.keys(source);

let valSrc = Object.values(source);

console.log(keySrc)

console.log(valSrc)

/*

Loop through all items in the `collection`

    Get an array of the keys from the current item

    Get an array of the values from the current item

*/

let array=[];

let currKeys = Object.keys(collection);

let currVals = Object.values(collection);

console.log(currVals);

currVals.map((x)=>{for(let i = 0; i < currVals.length; i++){

  if(x[currVals[i]]===keySrc || valSrc){array.push(x[currVals[i]])}

}});

console.log(array)

/*    If every source key is present in the current item's keys 

    and every source value is present in the current item's values

        Add the item to the return array

Return the array*/

  // Only change code above this line

  return arr

}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

Something seems off in this task.
Are the comments from you or are they provided in the task?

Because there is a massive issue: It’s comparing keys and values seperatly… Which doesn’t make sense. If given { last: "Capulet" } then my intuition would tell me, to look for all objects which contain { last: "Capulet" }, but by comparing keys and values seperatly, it would also qualify { first: "Capulet", last: "Frank" } despite the fact that “last” is “Frank” - because keys contain “last” and values contain “Capulet”.

But in my intuition, I’d think I have to check the presence of the keys and then the value behind THAT key and only have those objects qualify, which have the EXACT key-value-PAIR.

I thought that a simpler approach might be best. So, I want to use filter() since it makes sense to me. (I want to return the matching key value pair, so I should eliminate all those that don’t match the key value pair in source.

Yet, I wrote what I thought was a reasonable algorithm but it doesn’t work.
I’m thinking that that I’m not addressing the specific data type in my code and this is the reason that it is not working…but maybe there’s another problem?

Help please. Code below:

function whatIsInAName(collection, source) {

  const arr = [];

  //filter object array so that only elements which match that of the source remain

let collect = collection.filter(x=>x==source);

console.log(collect)

  // Only change code above this line

  return collect;

}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

Well the problem here is, that JavaScript compares objects by their memory adress, not their content. So that will always fail.

On top of that, just go through the code in your head…
Like, just look the one example that should be kept:
{ first: "Tybalt", last: "Capulet" } == { last: "Capulet" }
Even if JS could compare objects, what did you expect it to do? Look at an object with two entries, compare it to another with one and then be like “Yep, 2 is totally the same as 1, this is true”?

You cannot just jump around, throw whatever method you heard off at the problem and see what sticks.
You have to first figure out, how you would solve that problem by hand. Then when you got that down, you can think about methods and algorithms to do that job for you.

I am tossing different ideas at this problem but to no avail.

I don’t know how to penetrate this problem. These object arrays are always very difficult for me and I’m still not sure how to wrap my head around these data structures and manipulate them.

What I’d like is any resources people could point to where I could see these sorts of data structures explained in detail. I feel like I need this sort of focused refresher because I’m sure my problem is i don’t have the theoretical grounding to approach the problem.

If anyone can help, I’d greatly appreciate it.

Just trying code without a plan is a double edged sword. It can help you understand the data and the problem, but it rarely creates code that works.

Lets back up here.

Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument).

So, collection is an array of objects and source is an object.

Now lets look at the example

For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }] , and the second argument is { last: "Capulet" } , then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.

Ok, that’s hard to read, lets do some formatting

const collection = [
  { first: "Romeo",    last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt",   last: "Capulet" }
];
const source = { last: "Capulet" };

How would you by hand (seriously, don’t look up functions or say big computer words at me) go through this list and make a new list that has every person/object that has a matching last name? Pretend I’m a very rebellious child that will do only what you say I must and I will look for every opportunity to do your instructions incorrectly. What exactly do you want me to do in order to make this new list?

2 Likes

One course I really found useful from this point of view was Just Javascript by Dan Abramov, I don’t know if it can work for you though, but maybe check it out.

1 Like

Look, we want to help you, but we cannot help you, if you provide one approach, get some feedback and then try a vastly different approach - we cannot anticipate on what you might try next when not utilizing the feedback provided.

I know these data structures are hard to wrap your head around when starting out. My first contact with these kind of objects was on leetcode, where I noticed people managed to perform like 100times better than me, by using “{}” instead of “[]” and it took me a couple of days of understanding what the heck the difference is.

However if it’s hard, you need to focus on one thing.
Because frankly, the very first approach you wrote, was already very close. And then you straved away from it. It needed only a few adjustments to work out.

It’s good to look at some resources and examples as to how JSON work, because it’s certainly not as straightforward as other data-structure. It might also help to look at a video about hash-tables → because that’s what a JSON is. A hashtable is a datastrucute which uses keys to calculate a memory adress where a value to that key is stored. Because it works with memory-adresses, it can only compare those. “last” in one JSON refers to a different memory-adress than “last” in another object, hence they fail comparisons. That’s why something like “.hasOwnProperty()” is needed - to tell it, that you don’t want to compare memory-adresses calculated by some hash-function → but the actual plain data of the key AND ONLY the key. Because while we see basic key-value pairs, the computer sees a key, a hashfunction, a space in memory for ALL possible values for the hash-function, a specific adress given via the hash function for the given key and whatever is written in that adress.
That’s why in order to work with these, you have to consider working with keys and values separatly.

Also, you gotta need to look at some kind of documentation - like .hasOwnProperty() only looks for the presence of a key, so you cannot provide it with anything else but data suitable for a key. And keys have to be basic datatypes, so no JSON or whatnot can be given to this method.

I have questions. I’m taking all advice I’ve received in this thread and I’m working through it to try to figure out what’s happening.

This is a JSON object, yes?

Regardless of the answer there, my next question:

first and last do not have quotation marks around them. This leads me to believe that they are the keys and that “Mercutio” and “Capulet”… are the values. However, when I run Object.entries(collection) I see that the keys are numerals. Therefore, last and first are values? Are they key-value pairs nested within the value of another key-value pair?

No.

That’s just being advised because it’s a simple structure I think. JSON is a text format for transferring data, this is JS. JSON in a JS program would just be a string, it would be unusable without being translated to JS.

The way JSON looks is based on JS objects, but it’s nothing to do with JS otherwise and I think this is just confusing you.

What type of thing is collection?

Nope

Well, yes, sort of what type of thing is collection

An array object I assume, although I cannot penetrate it based on Dot Bracket Notation. At least in the way I’m doing it I can’t.

I tried collection[last] as a way of finding a matching value for source. This only gave me empty brackets. I was using a for loop to cycling through. I was thinking of a for…in loop, but if I can’t identify properties through just bracket/dot notation then I have no idea what to tell JS to look for in a for…in.

Right, so

What are the keys of an array? Hint: I can tell you what they are in any JS program ever written.

unless you’ve assigned a variable called last and it’s a number you assigned to it I’m not what you think collection[last] is going to do

This is what I meant by recommending that you don’t get so focused on syntax you want to use that you stop thinking about what you are doing.

The instructions big picture say what the collection is

Before you get wrapped up in the code you want to write using ‘Dot Bracket Notation’ (did you mean Dot Notation or Bracket Notation? Dot Bracket isn’t thing…) you need to be able to describe a process that will accomplish this task.

How do you check a list of people and make a new list of everyone who has a matching last name?

If you can describe that, that is a massive step forward from where you are

1 Like

from looking at your code, you aren’t comparing the right way.
x = { first: “Romeo”, last: “Montague” }
source = { last: “Capulet” }
x ≠ source