0

i haven't an idea of how to find the key in my json array.

if i checking finding key by function parameter it doesn't work.

Part of my json data:

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

This code return object correctly:

function getKey(json, key)
{
  console.log(key);//has string "myProductTitle"
  let obj = json.product.find(item => item.title === "myProductTitle");

  return obj;
}

This code return empty object:

function getKey(json, key)
{
  console.log(key);//has string "myProductTitle"
  let obj = json.product.find(item => item.title === key);

  return obj;
}

How to do this correctly?

Hasip Timurtas
  • 983
  • 2
  • 11
  • 20
mict
  • 11
  • 1
  • 3
  • Can you demonstrate your problem by creating a snippet with the "JavaScript/HTML/CSS snippet" button? – Guerric P Dec 03 '20 at 10:46
  • To check equality of the contente of string objects use == https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons/359509#359509 – Florent Dec 03 '20 at 10:56
  • It should work. Are you sure that the key is correct? I mean the key you are sending to the `getKey` function. – Patrik Braborec Dec 03 '20 at 10:49
  • It should work. Are you sure that the key is correct? I mean the key you are sending to the `getKey` function. – Patrik Braborec Dec 03 '20 at 10:49

3 Answers3

0

Use == to check equality of contetent of object string.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

so

  let obj = json.product.find(item => item.title == key);
Florent
  • 436
  • 3
  • 8
0

<!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>
Giovanni
  • 43
  • 6
0

I discovered the problem, var parameter "key" in function getKey was with a blank space "myProductTitle " is not equal to "myProductTitle" and the return of the function is undefined. I changed the function to eliminate blank spaces, a solution I took from

How to remove spaces from a string using JavaScript?

It runs OK even with strict equality (which I strongly suggest you to use to avoid undesirable effects).

I also left the original getKey function with some debbug code for you to check the problem yourself.

Hope I could help.

<!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>
Giovanni
  • 43
  • 6