Having problems with the For...In syntax in Javascript?

The search feature in this code snippet seems to be causing some trouble. I suspect that the issue lies within the For...In loop, however, my knowledge of JavaScript is still pretty new. Here is the snippet:

var contacts = {
john: {
    firstName: "john",
    lastName: "smith",
    number: 1,
    address: ["1"]
},
jane: {
    firstName: "jane",
    lastName: "smith",
    number: 2,
    address: ["2"]
}
};

var displayList = function(list) {
for(var item in list) {
    console.log(item);
}
};

var findContact = function(name) {

for(var contact in contacts) {
    if(contact.firstName === name) {
        console.log(contact);
        return contact;
    }
}
};

findContact("jane");

Answer №1

When using the for in loop, it iterates over the keys and not the values.

In the case where friends is a string holding the name of each property, you can access the corresponding value by using friends[friend].

Answer №2

Extensive resources on the for..in loop can be found on mdn. The variable is dynamically assigned to each property name during each iteration.

Consider optimizing your search function by utilizing hasOwnProperty method on the object:

var search = function(name) {
    if(friends.hasOwnProperty(name)){
        return friends[name];
    }
};

By doing this, you can verify the existence of a property with the name name within the object friends and return it. Refer to this EXAMPLE for a demonstration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

Cannot adjust Span content with JQuery

I am currently utilizing Bootstrap and JQuery for my project. HTML <div> <ul> <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li> </ul> </div&g ...

Stop the bubbling effect of :hover

How can the hover effect be prevented for the parent element when hovering over its children? Please take a look at the following code snippet: const parent = document.getElementById('parent') parent.onmouseover = function testAlert(e) { /* ...

Manipulating nested arrays using index values in JavaScript

Can someone assist me in sorting a multidimensional array based on the value of the first index? I've tried using a for loop without success. Looking for solutions in JS or jQuery. I want to convert the following array: var pinData = [ ['< ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

Troubleshooting a setTimeout filter problem in Vue

Implementing a notification system in Vue has been my latest project. I've created a Notifications component to store error messages that I want to display. data(){ return { alerts: { error: [] } ...

Tips for correctly storing an async/await axios response in a variable

I am facing a challenge with the third-party API as it can only handle one query string at a time. To overcome this limitation, I am attempting to split multiple strings into an array, iterate through them, and make async/await axios calls to push each res ...

Opt for CSS (or JavaScript) over SMIL for better styling and animation control

I recently noticed an alert in my Chrome console that SVG's SMIL animations are being deprecated and will soon be removed. The message suggested using CSS or Web animations instead. Since I want to transition from SMIL to CSS animations, there are a ...

Cropping and resizing images

Within my angular application, I have successfully implemented image upload and preview functionality using the following code: HTML: <input type='file' (change)="readUrl($event)"> <img [src]="url"> TS: readUrl(event:any) { if ...

What are some strategies to reduce the frequency of API calls even when a webpage is reloaded?

Imagine I'm utilizing a complimentary API service that has a restriction of c calls per m minutes. My website consists of a simple HTML file with some JavaScript code like the one below: $(function () { //some code function getSomething() { ...

What seems to be the problem at hand, and where exactly is the issue located?

import React from 'react'; const card = ({name, email, id}) => { return( <div className='tc bg-light-green dib br3 ma2 grow bw2 shadow-5'> <img alt="robots" src = {'https://uniqueimage. ...

Retrieving URL from AJAX Request in Express JS

Currently, I am in the process of developing an Express App and encountering a challenge regarding the storage of the user's URL from which their AJAX request originated. In simpler terms, when a website, such as www.example.com, sends an HTTP request ...

Dealing with Koa-router and handling POST requests

I am facing an issue handling POST requests in my koa-router. Despite using koa-bodyparser, I am unable to receive any data sent through my form. My template engine is Jade. router.js: var jade = require('jade'); var router = require('koa- ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Steps for dynamically adjusting form fields depending on radio button selection

I am looking to create a dynamic form that changes based on the selection of radio buttons. The form includes textfields Field A, Field B, ..., Field G, along with radio buttons Radio 1 and Radio 2. I need to update the form dynamically depending on which ...

Exploring the Modularity of Post Requests with Node.js, Express 4.0, and Mongoose

Currently, I am immersed in a project that involves utilizing the mean stack. As part of the setup process for the client-side, I am rigorously testing my routes using Postman. My objective is to execute a post request to retrieve a specific user and anot ...

Using Angular to make GET requests with JSON data in PHP

Seeking assistance with connecting Angular frontend to PHP backend. Upon calling the service, I am receiving an empty array in the console. Controller: angular.module('pageModule') .controller('pageController', ['$scope', &a ...

Showing JSON information fetched from an AJAX request within an HTML page

I've been working on a project and I'm almost there with everything figured out. My main challenge now is to display an array of items on a web page after making an ajax call. Below is the code snippet I currently have: JQuery Code: var su ...

ReactJS: streamlining collection method calls using re-base helper functions

I have been struggling to find a way to integrate ReactJS with firebase. Fortunately, I came across the amazing re-base repository which perfectly fits my needs. fb-config.js var Rebase = require('re-base'); var base = Rebase.createClass({ ...

Unleashing the power of eventListeners through exponential re-rendering upon state updates

Trying to implement an eventListener for "keydown" to update the state (a boolean named showMenu). I placed it inside a useEffect, but it's not functioning correctly and I can't pinpoint the issue. When I include showMenu in the dependency arra ...