javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array.

When I try to find the key using a function parameter, it does not seem to work.

This is a snippet of my json data:

...
{
  "product": [
    {
      "title": "myProductTitle",
...

The following code successfully returns an object:

function retrieveKey(json, key)
{
  console.log(key); // should be "myProductTitle"
  let obj = json.product.find(item => item.title === "myProductTitle");

  return obj;
}

However, this code returns an empty object:

function retrieveKey(json, key)
{
  console.log(key); // should be "myProductTitle"
  let obj = json.product.find(item => item.title === key);

  return obj;
}

What is the correct way to accomplish this task?

Answer №2

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  
    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }

      .btn-group
      {
        padding: 10px;
      }

    </style>

  </head>
  <body>
    <header>
      <div class="navbar navbar-dark bg-dark shadow-sm">
          <a href="#" class="navbar-brand d-flex align-items-center">
            <strong>Cfg</strong>
          </a>
      </div>
    </header>

<main role="main" id="products"></main>

<script type="text/javascript">

jQuery(document).ready(function($){

  var html="";
  var jsonResponse;
  var products=[];

  //$.getJSON("http://127.0.0.1:8080/data.json", function( jsonResponse ) {
    jsonResponse=JSON.parse( 
     `{
    "product": [
    {
      "title": "myProductTitle",
      "description": "myProductTitle",
      "img": "http://localhost:8080/myProductTitle.jpg",
      "power" : 123,
      "cost":1000,
      "solarpowered":[
        {
          "possible":true,
          "cost":1000,
          "autonomyday":2
        }
      ],
      "constpowered":[
        {
          "possible":true,
          "cost":1000,
          "autonomyday":1
        }
      ],
      "nightpowered":[
        {
          "possible":true,
          "cost":1000,
          "autonomyday":1
        }
      ]
      
    }]}`
    );

  //console.log(jsonResponse);
  
  jsonResponse.product.map(product => {
  products.push(product.title);
  });
  //console.log(products);
  
  $('main#products').html(render("Select product",products));

  $(".dropdown-item").click(function(e){
    //console.log(e.target.innerHTML);
    $('main#products').html(render(e.target.innerHTML,products,jsonResponse));

    $('main#products').append(render(e.target.innerHTML,products));
    //buttons[e.srcElement.id].innerText=e.srcElement.innerHTML;
    //console.log(e);
  });

//products.map(d => console.log(d));
//});

});

function getKey(json, key)
{
  var key2=key.toString();
  console.log(key2);// right value
  let obj = json.product.find(item => item.title == key);

  return obj;
}

function render(title, dropdowns, json)
{
  if(typeof json == 'object')
  {
    //debugger
    
    
    //json.product.map(product => {
    console.log(getKey(json,title));// but result is empty
 //});
  }

  html=    ` <div class="card mb-3" style="max-width: 540px;">

<div class="btn-group">
  <button type="button" id="b1" class="btn btn-primary dropdown-toggle btn-lg"
   data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
   data-placeholder="header">
   `+ title + `
  </button>
  <div class="dropdown-menu">
   ` + (dropdowns.map(d => `<a class="dropdown-item">${d} </a>` )) + `
  </div>
    
  </div>  

  <div class="row no-gutters">
    <div class="col-md-4">
      <!-- <img src="..." class="card-img" alt="..."> -->
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title" data-placeholder="title"></h5>
        <p class="card-text" data-placeholder="description"></p>
      </div>
      
    </div>
  </div>
</div>`

return html;

};

</script>
</html>

Answer №3

After identifying the issue, I realized that the problem with the "key" variable in the getKey function was caused by an extra space - "myProductTitle " is not the same as "myProductTitle", leading to an undefined return value. To resolve this, I updated the function to remove any spaces, a solution inspired by

How to remove spaces from a string using JavaScript?

The updated function now works fine even with strict equality (which I highly recommend for avoiding unexpected outcomes).

I've also kept the original getKey function with some debug code so you can investigate the problem on your own.

I hope this information proves helpful to you.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  
    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }

      .btn-group
      {
        padding: 10px;
      }

    </style>

  </head>
  <body>
    <header>
      <div class="navbar navbar-dark bg-dark shadow-sm">
          <a href="#" class="navbar-brand d-flex align-items-center">
            <strong>Cfg</strong>
          </a>
      </div>
    </header>

<main role="main" id="products"></main>

<script type="text/javascript">

jQuery(document).ready(function($){

  var html="";
  var jsonResponse;
  var products=[];

  //$.getJSON("http://127.0.0.1:8080/data.json", function( jsonResponse ) {
    jsonResponse=JSON.parse( 
     `{
    "product": [
    {
      "title": "myProductTitle",
      "description": "myProductTitle",
      "img": "http://localhost:8080/myProductTitle.jpg",
      "power" : 123,
      "cost":1000,
      "solarpowered":[
        {
          "possible":true,
          "cost":1000,
          "autonomyday":2
        }
      ],
      "constpowered":[
        {
          "possible":true,
          "cost":1000,
          "autonomyday":1
        }
      ],
      "nightpowered":[
        {
          "possible":true,
          "cost":1000,
          "autonomyday":1
        }
      ]
      
    }]}`
    );

  //console.log(jsonResponse);
  
  jsonResponse.product.map(product => {
  products.push(product.title);
  });
  //console.log(products);
  
  $('main#products').html(render("Select product",products));

  $(".dropdown-item").click(function(e){
    //console.log(e.target.innerHTML);
    $('main#products').html(render(e.target.innerHTML,products,jsonResponse));

    $('main#products').append(render(e.target.innerHTML,products));
    //buttons[e.srcElement.id].innerText=e.srcElement.innerHTML;
    //console.log(e);
  });

//products.map(d => console.log(d));
//});

});

// function getKey split string into arr chars, you can see the blank space last char of key var

/*
function getKey(json, key)
{
   let obj = json.product.find(item =>{console.log(item.title.split(''),key.split(''));return item.title == key});

   return obj;
}
*/

// function getKey modified, using strict equality

function getKey(json, key)
{
   key = key.replace(/\s+/g, '');
   let obj = json.product.find(item => item.title === key);

   return obj;
}



function render(title, dropdowns, json)
{
  if(typeof json == 'object')
  {
    //debugger
    
    
    //json.product.map(product => {
    console.log(getKey(json,title));// but result is empty
 //});
  }

  html=    ` <div class="card mb-3" style="max-width: 540px;">

<div class="btn-group">
  <button type="button" id="b1" class="btn btn-primary dropdown-toggle btn-lg"
   data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
   data-placeholder="header">
   `+ title + `
  </button>
  <div class="dropdown-menu">
   ` + (dropdowns.map(d => `<a class="dropdown-item">${d} </a>` )) + `
  </div>
    
  </div>  

  <div class="row no-gutters">
    <div class="col-md-4">
      <!-- <img src="..." class="card-img" alt="..."> -->
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title" data-placeholder="title"></h5>
        <p class="card-text" data-placeholder="description"></p>
      </div>
      
    </div>
  </div>
</div>`

return html;

};

</script>
</html>

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

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...

Hide the scrollbars on the sidebar

I'm attempting to recreate a sleek scrollbar that caught my eye on the website . To achieve this, I need to have a screen larger than 955px in order to display the sidebar. However, when my sidebar overflows in the y direction, it causes an additional ...

Leveraging API JSON information in conditional return statements with React

Working on a small Express/React app (not for production), I am validating a hashed pin in express and returning either message: false if validation fails or message: <cardnumber> if validation is successful. Currently, in my react frontend, I am try ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

The conversion of an org.json.JSONObject type to a JSONArray within an Android JSONObject is not possible

I am currently working on extracting data from a JSONObject that includes an array of user details. My current task involves retrieving the username from this json object. If you would like to view the JSON data, please click here. So far, I have succes ...

Gson Deserialization of json data fails to function properly

Class holds all the music tracks public class Songs{ private List levels; public List getLevels() { return levels; } public void setLevels(List levels) { this.levels = levels; } } each track has its own properties ...

Create a video player in your HTML code using the class "afterglow", and also link a separate class to it for additional styling

I'm encountering some challenges with a project that involves a JS file for a Bootstrap modal popup and an HTML5 video player. The issue I'm facing is that I am unable to link the class for the video player theme. Can anyone here assist me in ide ...

Error: Unable to locate command "start" when running `yarn start`

When I run 'yarn start' command, I encounter an error message stating that the command "start" was not found. Could this issue be due to the absence of a script tag in my package.json file? Any suggestions on how to resolve this?</p> <p& ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

Image renders only on a single page in Express.js

I am facing an issue while attempting to display an image on multiple pages using Pug and Express. The image should be visible on the routes '/', 'data', and 'update'. While it is successfully displayed on the root '/&ap ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Fetch the information, insert following, and trigger a slide toggle

I am new to jQuery and I want to create a sliding table. The original table has 3 levels: <ul class="categories"> <li id="category1">1 element</li> //parentid=0 <li id="category2">2 element</li> //parentid=0 <ul> < ...

The Ajax success callback unexpectedly displays the number "1" in the top left corner of the empty page instead of updating the specified div

Currently, I am in the process of developing a Yii2 application. I have encountered an issue where I select data from a Bootstrap modal popup and submit it to a controller action that contains an insert query. The problem arises after submitting the data f ...

Clear HTML

Is there a way to create a 'div' element in an HTML document and adjust the background transparency using CSS or Javascript/JQuery in order to achieve a look similar to Simple Calendar Widget or Glass Widgets from Android? I have tried using the ...

Employing a JSON callback within a different function

Can someone help me figure out how to use a getJSON result obtained in one function in another function? I am trying to fetch text from an input and search flickr for related images. Later, I need to use the JSON data retrieved to display those pictures o ...

A controller in Angular.js that leverages several different services

I'm having trouble injecting multiple services into a controller. Here are my listed files: index.html file: <script src="'./angular/angular.min.js'></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta ...

Is it necessary to release a new library version for non-functional updates?

As the maintainer of several JavaScript libraries, I often find myself needing to update dependencies that don't necessarily require any functional changes. This is especially true when my library is not impacted by a breaking change in one of its dep ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

I'm grappling with a JavaScript issue and need some help. You can find the demo of the functioning script by the author right here. I've implemented the same code as displayed on his demo page. I've downloaded the worker.js file and ...

Executing an HTML webpage with npm package.json file

I have recently discovered package.json files and am new to using them. I have created an HTML webpage using three files: HTML, CSS, and JavaScript. Currently, I open the HTML file directly in my browser but have been advised to use a package.json file a ...