Exploring an object to find the value of an array

Here is the object that I am working with:

var list = {
  nums: [
    [117],
    [108]
  ],
  numsset: [
    [2256, 2265],
    [234],
    [3445, 3442]
  ]
};

Imagine there is an input field on the page where a user can type a number. How can I search the object for that value and return the corresponding key?

Input      Returned
108        nums
3445       numsset
2872       
2265       numsset

I tried looping through the object but did not get the desired result.

Any assistance you can provide would be greatly appreciated. Thank you in advance.

Answer №1

Below is the code snippet that is functioning properly:

const data = {
  numbers: [
    [117],
    [108]
  ],
  numberSet: [
    [2256, 2265],
    [234],
    [3445, 3442]
  ]
};

const determineElement = (value) => {
  let keyFound = '';
  
  Object.keys(data).some((key) => {
    const array = data[key];
    
    const foundData = array.some(element => element.includes(value));
    
    if (foundData) {
    keyFound = key;
      return true;
    }
    
    return false;
  })
  
  return keyFound;
}

console.log(determineElement(2256));
console.log(determineElement(108));
console.log(determineElement(222));

Answer №2

One technique is to create a hash table and save the keys associated with the given numbers.

var list = { nums: [[117], [108]], numsset: [[2256, 2265], [234], [3445, 3442]] },
    keys = {};

Object.keys(list).forEach(key => list[key].forEach(arr => arr.forEach(value => keys[value] = key)));

console.log(keys);

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

Ways to calculate the total number of keys within a JSON object at a certain level

I need to process a JSON file by extracting values from keys located at a specific depth. The initial value I want to access is situated here: json.children[0].children[0].children[0] Is there a method to navigate through the JSON object at a particular ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...

Children can easily access multiple items within a list by using the ul tag

I am struggling with changing the class of ul inside the ul.navigator. I want to change it only when I click on a particular li, but my current approach doesn't seem to be working. Can anyone provide some guidance or assistance? $('.navigator& ...

"Is it possible for a JSON array to have a length of zero even

After receiving a JSON response from the server and converting it into a Javascript object, the structure looks like this: var response = { key1:[], key2:[], key3:[], key4:[], key5:[] } Once the request is complete, the response objec ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...

How can I prevent query string parameters from being sorted in React Router?

I'm having trouble setting a Route path with a query string using react-router. The issue is that react-router always arranges query params alphabetically, resulting in a sorted query string in the URL. For instance, on a location filter page where I ...

Efficiently updating arrays within object arrays using MongoDB

I have the following data structure: { data: [ {pos:"0", moreData: ["a", "b"] }, {pos:"1", moreData: ["a", "c"] }, ]} I want to update this structure by adding a letter to moreData where pos ...

Vue fails to parse the API

I am currently developing a Vue application that needs to fetch real-time data from an API. However, I am encountering difficulties in reading the data from the API. The API that is working fine for me is located at: Google API However, when I try to acc ...

Having trouble retrieving req.user in Passport.js within Express.js?

req.user is only accessible within its original function. I recently learned that passport automatically attaches the user to each request after authentication. In order to prevent users from bypassing the login page by accessing inner pages directly thr ...

Issue encountered post installation on host including telemetry.js

I'm encountering an issue while attempting to compile my Gatsby JS website on Netlify. Can anyone provide insight into what might be causing this error? Error: 4:53:02 PM: $ gatsby build 4:53:02 PM: /opt/build/repo/node_modules/gatsby-telemetry/lib/t ...

Node js guide: Generating secure passwords with nonce, timestamp, and password

Currently, I am working on developing an app using Express and need to make a SOAP API request. The API requires sending nonce, timestamp, and digest password. Initially, I successfully implemented this functionality using PHP. Now, I want to achieve the s ...

What approach can be taken to establish a dependency between an AngularJS controller and a value that is retrieved through ajax and loaded onto the root

I have an app that loads like this: app.js file: angular.module('App', []).run(['$rootScope', '$q', 'SessionManager', 'EndpointService', function ($rootScope, $q, SessionManager, EndpointService) { $r ...

The KML file cannot be read by the Google Maps KML Layer

I'm currently facing an issue with reading a simple KML file using Google Maps API 3. I have created the KML file in Google Maps Editor and I am using the google sample codes, but I can't seem to identify where the problem lies. gm-sample.html ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

Adjusting text sizes using HTML and JavaScript

I stumbled upon some code that allows website visitors to change font size at this link. I modified the code to make use of buttons for this functionality. <html> <head> <script language="JavaScript" type="text/javascript"> function cha ...

I keep encountering an error in the where clause when trying to update MySQL. What could be

I encountered an issue stating Unknown column 'CR0001' in 'where clause' while executing my code. Strangely, the error seems to be related to the id_scooter column rather than CR0001. Below is the snippet of my code: var update = "UPDA ...

Verify the authenticity of a date using the locale parameter in the Intl API

Seeking advice for validating inputfield based on locale argument. How to format dates differently depending on the specified locale? For example, if locale is 'en-uk' then date should be in mm/dd/yyyy format, but if locale is 'de-ch' i ...

What could be causing the failure to retrieve the salt and hash values from the database in NodeJS?

My current issue involves the retrieval of hash and salt values from the database. Although these values are being stored during sign up, they are not being retrieved when needed by the application. Below, you will find snapshots of the database, console s ...

Utilizing Lambda to Analyze PDF Documents with AWS Textract

Struggling with implementing Textract in Lambda to analyze PDF documents using JavaScript. Any assistance would be greatly appreciated. Below is the code snippet: const AWS = require("aws-sdk"); AWS.config.update({ region: proces ...