The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only able to retrieve the indexes and not the actual names like 'sports' or 'technology' for comparison.

I am unsure if my JSON array is structured correctly for this task, but I am open to making adjustments as needed.

Any suggestions on how to approach this?

[  
   {  
      "sports":{  
         "image":"",
         "text":"\u003Cp\u003EWe believe businesses that are people-focused and have a well-defined story are poised for success. That\u2019s why we bring together branding and ownable experience design for our clients. Lorem ipsum dolor sit amet, consectetuer adipiscing.\u003C\/p\u003E"
      }
   },
   {  
      "media---entertainment":{  
         "image":"",
         "text":""
      }
   },
   {  
      "lifestyle":{  
         "image":"",
         "text":""
      }
   },
   {  
      "technology":{  
         "image":"",
         "text":""
      }
   },
   {  
      "education":{  
         "image":"",
         "text":""
      }
   }
]

Would restructuring the JSON array like this be more effective?

[
   {
      "sports":{
         "image":"",
         "text":"\u003Cp\u003EWe believe businesses that are people-focused and have a well-defined story are poised for success. That\u2019s why we bring together branding and ownable experience design for our clients. Lorem ipsum dolor sit amet, consectetuer adipiscing.\u003C\/p\u003E"
      },
      "media---entertainment":{
         "image":"",
         "text":""
      },
      "lifestyle":{
         "image":"",
         "text":""
      },
      "technology":{
         "image":"",
         "text":""
      },
      "education":{
         "image":"",
         "text":""
      }
   }
]

The PHP code used to generate the JSON looks like this:

$clientsSectorsArray = array();
foreach ($sectors as $sector) {
    $clientsSectorsArray[] = array(
        "{$sanitizer->pageName($sector->global_text)}" => array(
            "image" => "{$sector->global_image->url}",
            "text" => "{$sector->global_textarea}",
        )
    );
}
$clientsSectors = json_encode($clientsSectorsArray);

Answer №1

The original version presents a flawed structure with an array of objects where each object possesses a unique key. Despite this, it can still be utilized in the following manner:

item = data.find(obj => Object.keys(obj)[0] == searchString);
if (item) {
    image = item.image;
    text = item.text;
}

The alternative version offers simplicity by allowing the search string to directly serve as a dynamic property name.

item = data[0][searchString];

However, the unnecessary wrapping of data in an additional array level should be avoided. The data can be structured like this instead:

$clientsSectorsArray = array();
foreach ($sectors as $sector) {
    $clientsSectorsArray[$sanitizer->pageName($sector->global_text)] = array(
        "image" => "{$sector->global_image->url}",
        "text" => "{$sector->global_textarea}",
        );
}
$clientsSectors = json_encode($clientsSectorsArray);

This arrangement will generate the following JSON output:

{
  "sports":{
     "image":"",
     "text":"\u003Cp\u003EWe believe businesses that are people-focused and have a well-defined story are poised for success. That\u2019s why we bring together branding and ownable experience design for our clients. Lorem ipsum dolor sit amet, consectetuer adipiscing.\u003C\/p\u003E"
  },
  "media---entertainment":{
     "image":"",
     "text":""
  },
  "lifestyle":{
     "image":"",
     "text":""
  },
  "technology":{
     "image":"",
     "text":""
  },
  "education":{
     "image":"",
     "text":""
  }
}

Subsequently, JavaScript can be employed in the following manner:

item = data[searchString];

Answer №2

To demonstrate how straightforward it is to utilize JSON data, I have created a sample project:

https://jsfiddle.net/gwLyn7ja/

Below is the HTML code:

<button>sports</button>
<button>media---entertainment</button>
<button>lifestyle</button>
<button>technology</button>
<button>education</button>
<button>health</button>

<textarea name="" id="" cols="30" rows="10"></textarea>

And here is the JavaScript code using jQuery:

const ob = {
      "sports":{
         "image":"",
         "text":"sports text"
      },
      "media---entertainment":{
         "image":"",
         "text":"media text"
      },
      "lifestyle":{
         "image":"",
         "text":"lifestyl text"
      },
      "technology":{
         "image":"",
         "text":"tech text"
      },
      "education":{
         "image":"",
         "text":"education text"
      }
   };

function getObText(key) {
  if (ob[key]) {
    return ob[key].text
  } else {
    return 'key not found';
  }
}

$('button').on('click', function(){
    const key = $(this).text();
    const txt = getObText(key);
    $('textarea').val(txt);
})

Answer №3

Is this acceptable for your requirements?

// Haven't gotten the data yet
const personalData = ... 

const interests = ["music", "fashion"]
filteredResults = personalData.filter(item => {
    for(let interest of interests)
        if(!item.hasOwnProperty(interest))
            return false
    return true
})

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

The value returned by EntityRecognizer.resolveTime is considered as 'undefined'

In my bot's waterfall dialog, I am utilizing the LuisRecognizer.recognize() method to detect datetimeV2 entities and EntityRecognizer.resolveTime() to process the response. Here is an example of how I have implemented it: builder.LuisRecognizer.recog ...

Utilizing a CSS identifier with jQuery

I'm struggling with a basic .each statement for comments where I want a form at the bottom to add new comments. The goal is simple - when someone submits a comment, I want it to display just above and move the form down using jQuery. Although this fun ...

The data-src tags are functioning properly in the index.html file, but they are not working correctly in angular

I'm still learning about Angular and JavaScript, so please bear with me if my questions seem silly. I've been trying to add a theme to my Angular project. When I include the entire code in index.html, everything works fine. However, when I move ...

The function auth.createUserWithEmailAndPassword is not recognized in the context of React

base.jsx: import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; const firebaseConfig = { config }; export const app = initializeApp(firebaseConfig); export const auth = getAuth(); Register.jsx ...

"Encountering an issue with TestCafe's Selector - usage of the .find()

I've been having difficulty defining a selector in TestCafe using the ".find" method. My goal is to click on the link "Start a claim" as shown in the image below: Even though I'm using the id element and trying to navigate to the link with ".fin ...

Ways to verify if JSON.parse fails or yields a falsy outcome

Objective: const jsonData = JSON.parse(this.description) ? JSON.parse(this.description) : null When executing the above statement, my aim is to have the ability to parse a value successfully and return null if parsing fails. However, instead of achieving ...

Tips for correctly implementing Headers in AngularJS version 1.6

Currently, I am attempting to incorporate headers in a GET request using the $http method. This is the snippet of code that I have implemented: this.http.defaults.headers.common['Authorization'] = 'Bearer mytoken123123'; this.http.def ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

Ways to retrieve the value of the variable within the confines of this particular

In my code, I have private variables in the constructor and public variables in the class. To reference these variables and functions, I use the "this" keyword. However, when trying to access these variables inside a function, I am getting an "undefined" ...

Invoke a separate function after a successful Ajax request

I am currently working on an AJAX call in MVC3 and here is the snippet of code I have: save: function () { $.ajax({ url: "@Url.Action("Save")", type:"post", data: ko.toJSON(this), contentType:"applic ...

Deciphering intricate JSON structures using PHP

In my current situation, I am receiving a server response with mixed data and now I need to handle it using PHP. Array ( [14424174] => Array ( [0] => Array ( [id] => 45 ...

Incorporating text sections into a div container and adjusting the width

Currently facing an issue with the canvas element on my project. <div id="app-container"> <div id="canvas-container"> <div id="canvas"></div> </div> </div> In the CSS stylesheet, the following styles ar ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Using $state outside of the AngularJS environment

Currently, I am working on an AngularJS application that is meant to be a hybrid mobile app for both android and iOS platforms. Within the project, there is a JavaScript file that does not belong to any module. In this particular JavaScript file, I need to ...

steps for executing a Google script

In my program, the structure is as follows: // JavaScript function using Google Script 1. function F1() { ...... return (v1); } // HTML code for Google 1. <script> 2. function F2() { 3. alert ( 1 ); 4. function F2(); 5. alert ( 2 ); 6 ...

What is the best way to generate a box when a button is pushed?

How can I make a button create a box with text inside it when clicked? <div class="trades"> </div> <button onclick="create()">add</button> Here is the JavaScript function to create the box: function create() { var box = docu ...

Mongoose fails to carry out internal query using Promise mechanism

Just diving into the asynchronous and await world, I decided to play around with Mongoose + MongoDB + Node.JS. Here is a snippet of my code: exports.updateBrandPreferences = async (req,res) => { var userID = req.body.playerID; var newBrands = r ...

Efficient and precise floating-point number presentation

After updating a Lua JSON implementation, I made a significant change by replacing "%.14g" with "%.17g" for number formatting to prevent loss of precision. Using "%.17g" ensures that 17 digits are used, allowing for the conver ...

Saving a MongoDB document within an array in Node.js and retrieving it

I am working on retrieving specific documents from MongoDB using Node.js and storing them in an array. const getStockComments = async (req) => { const stockname = req.params.stockName; var comments = []; var data = []; const stock = await sto ...

How to successfully configure environment variables in Next.js and deploy them on Netlify

An issue arose after deploying my Next.js application to Netlify using Git. I utilize a .env.local file to store the backend route URL that is used across the entire app for fetch requests. However, post deployment, the process.env.NEXT_PUBLIC_BACKEND_ROUT ...