What is the shortest method for locating a string value within an array object?

I am dealing with a range of status codes stored in an object retrieved from an API. The structure looks like this:

{
  "location": [
    "HOME_ADDRESS_INCOMPLETE",
    "HOME_MISSING_ADDRESS"
  ],
  "basics": [
    "HOME_MISSING_TYPE"
  ],
  ...
}

Each key, such as location, corresponds to a step in a setup wizard for the user based on the missing elements represented by constants like HOME_ADDRESS_INCOMPLETE.

What would be the most efficient way to take this object and one constant, say MISSING_CURRENCY, and determine the key associated with that constant's array?

This is my current attempt, but it only returns the array itself:

const activeStep = Object.values(HomeStatusCodes).filter(statusArray => {
  return statusArray.includes(homeActivationResponse.code)
})

Answer №1

Array#find (on the array of keys from that particular structure, obtained using Object.keys) along with Array#indexOf can accomplish this task:

function findValue(item) {
  return Object.keys(database).find(function(key) {
    return database[key].indexOf(item) != -1;
  });
}

Please note that Array#find was introduced in ES2015, however, it is possible to shim/polyfill it.

For example:

var database = {
  "location": [
    "HOME_ADDRESS_INCOMPLETE",
    "HOME_MISSING_ADDRESS"
  ],
  "basics": [
    "HOME_MISSING_TYPE"
  ],
  "description": [
    "HOME_MISSING_DESCRIPTION"
  ],
  "immersions": [
    "AT_LEAST_ONE_STAY_REQUIRED",
    "SIMPLE_STAY_MISSING_HOURS",
    "SIMPLE_STAY_MISSING_OFFERED_LANGUAGES",
    "TANDEM_STAY_MISSING_HOURS",
    "TANDEM_STAY_MISSING_OFFERED_LANGUAGES",
    "TANDEM_STAY_MISSING_INTERESTED_LANGUAGES",
    "TEACHER_STAY_MISSING_HOURLY_PRICE",
    "TEACHER_STAY_MISSING_OFFERED_LANGUAGES",
    "TEACHER_STAY_MISSING_WEEKLY_PACKAGES"
  ],
  "rooms": [
    "NO_ROOMS"
  ],
  "photos": [
    "AT_LEAST_ONE_HOME_IMAGE_REQUIRED"
  ],
  "pricing": [
    "MISSING_CURRENCY",
    "SERVICE_WITHOUT_PRICE",
    "DISCOUNT_WITHOUT_PERCENT",
    "ROOM_WITHOUT_PRICE"
  ]
};

function findValue(item) {
  return Object.keys(database).find(function(key) {
    return database[key].indexOf(item) != -1;
  });
}

console.log(findValue("MISSING_CURRENCY"));

If you prefer a more concise syntax using ES2015:

const findValue = item =>
  Object.keys(database).find(key => database[key].indexOf(item) != -1);

(Yes, this indeed is a function.) You can test this live in browsers supporting ES2015 by running the following code:

var database = {
  "location": [
    "HOME_ADDRESS_INCOMPLETE",
    "HOME_MISSING_ADDRESS"
  ],
  "basics": [
    "HOME_MISSING_TYPE"
  ],
  "description": [
    "HOME_MISSING_DESCRIPTION"
  ],
  "immersions": [
    "AT_LEAST_ONE_STAY_REQUIRED",
    "SIMPLE_STAY_MISSING_HOURS",
    "SIMPLE_STAY_MISSING_OFFERED_LANGUAGES",
    "TANDEM_STAY_MISSING_HOURS",
    "TANDEM_STAY_MISSING_OFFERED_LANGUAGES",
    "TANDEM_STAY_MISSING_INTERESTED_LANGUAGES",
    "TEACHER_STAY_MISSING_HOURLY_PRICE",
    "TEACHER_STAY_MISSING_OFFERED_LANGUAGES",
    "TEACHER_STAY_MISSING_WEEKLY_PACKAGES"
  ],
  "rooms": [
    "NO_ROOMS"
  ],
  "photos": [
    "AT_LEAST_ONE_HOME_IMAGE_REQUIRED"
  ],
  "pricing": [
    "MISSING_CURRENCY",
    "SERVICE_WITHOUT_PRICE",
    "DISCOUNT_WITHOUT_PERCENT",
    "ROOM_WITHOUT_PRICE"
  ]
};

const findValue = item =>
  Object.keys(database).find(key => database[key].indexOf(item) != -1);

console.log(findValue("MISSING_CURRENCY"));

Answer №2

If you need to search for a specific item within an object, one approach is to iterate through the keys and identify the key that contains the desired value.

function findKey(object, item) {
    return Object.keys(object).find(key => object[key].includes(item));
}

var data = { "location": ["HOME_ADDRESS_INCOMPLETE", "HOME_MISSING_ADDRESS"], "basics": ["HOME_MISSING_TYPE"], "description": ["HOME_MISSING_DESCRIPTION"], "immersions": ["AT_LEAST_ONE_STAY_REQUIRED", "SIMPLE_STAY_MISSING_HOURS", "SIMPLE_STAY_MISSING_OFFERED_LANGUAGES", "TANDEM_STAY_MISSING_HOURS", "TANDEM_STAY_MISSING_OFFERED_LANGUAGES", "TANDEM_STAY_MISSING_INTERESTED_LANGUAGES", "TEACHER_STAY_MISSING_HOURLY_PRICE", "TEACHER_STAY_MISSING_OFFERED_LANGUAGES", "TEACHER_STAY_MISSING_WEEKLY_PACKAGES"], "rooms": ["NO_ROOMS"], "photos": ["AT_LEAST_ONE_HOME_IMAGE_REQUIRED"], "pricing": ["MISSING_CURRENCY", "SERVICE_WITHOUT_PRICE", "DISCOUNT_WITHOUT_PERCENT", "ROOM_WITHOUT_PRICE"] };

console.log(findKey(data, 'MISSING_CURRENCY'));

Answer №3

To optimize efficiency, I recommend utilizing a lookup map:

const statusCodeMap = new Map();
for (const type in ResponseStatusCodes) {
    for (const code of ResponseStatusCodes[type])
        statusCodeMap.set(code, type);

This approach allows for concise and effective usage:

const responseCodeType = statusCodeMap.get(apiResponse.code);

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

Swap the value of a button's text using a dropdown list when clicked in VueJS with TypeScript

I have a button with a click event that opens a dropdown list. I would like for the button text to be updated and for the selected option to be removed from the dropdown list when the user makes a selection. Currently, using {{interestSortingOptions.label} ...

Webpack 4 Failing to Properly Render Select Tag

I am encountering an issue with a basic select element that is not displaying correctly due to Webpack. The screenshot below illustrates the final rendered page source, where the closing tag for the select element has been incorrectly positioned before the ...

Having trouble getting past the initial iteration in Angular's modal system?

Having trouble generating a modal for every iteration in ngFor. The data passed to the modal seems to be stuck in the first iteration and doesn't change with each iteration. Any ideas on how to solve this? <div class="container"> & ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

Printing Strings in JavaScript IF Conditional Block

Hello there! I am looking for assistance with a JavaScript concept. Recently, I created some code where in the HTML file, there is a div element with an id of "GetID" where the string outputs are meant to be displayed. The JavaScript code looks something ...

From javascript to utilizing ajax calls to interact with php scripts,

I am currently working on a page called edit.php where I need to pass a JavaScript variable to a modal window containing PHP in order to execute a query and retrieve data. Unfortunately, my experience with Ajax is limited and I haven't been able to fi ...

Using Conditional Statements for Dynamic SVG Rendering in React

As I delve into React development, I encounter an interesting challenge with an object structure that goes a little something like this: [{ "title": "instagram", "href": "http://instagram.com" "class": &q ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Multiple sources are able to access and modify the data stored in one data.json file

I am aiming to utilize the data from a JSON file ("data.json") in both my Java application and node.js application. The Java application will read the JSON file, make any necessary changes, and rewrite the file with updated or new JSON objects. Similarly ...

Creating a dropdown button with three dots in a table row using jQuery

I've been working with tables and I'm trying to create a dropdown list with 3 dots in each table row. I've experimented with a few libraries and custom dropdown options, but none of them seem to be working properly. What I'm looking fo ...

What is the best way to extract data from a textfield, store it in an integer array, and then have it appear in a label?

I'm encountering errors with the following code where my output appears as symbols. I am working in Java using Netbeans GUI Builder. String[] stringValues = jTextField1.getText().split("[,]"); int[] numArray= new int[stringValues.length]; ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Navigation buttons that move the user either up or down the page

I am a beginner in programming and I wanted to create two buttons for my webpage. One button should appear when the page is scrolled more than 300px and take the user to the top, while the other button should be displayed immediately and scroll the user to ...

Dynamically loading iframes with JQuery

I have implemented a jQuery script to load another URL after a successful AJAX request. $(document).ready(function() { var $loaded = $("#siteloader").data('loaded'); if($loaded == false){ $("#siteloader").load(function (){ ...

I'm encountering a CastError while attempting to delete data in mongodb using Id

Encountered an issue while attempting to delete a MongoDB entry using the 'findByIdAndRemove' function in Mongoose. Specifically, it is throwing a 'Cast to ObjectId failed for value error'. Delete Service routes.delete('/:id' ...

ng-bind-html not refreshed following ng-click triggering

Recently, I started learning about the MEAN stack. I have implemented an ng-repeat in my HTML code that displays a list of titles. Each title has an ng-click function attached to it, which is supposed to show more details in an overlay popup. blogApp.co ...

Steps for ensuring that a script is loaded after the page has fully loaded

Is there a way to make the progress bar begin its loading animation after the `onload` loader animation has completed? Check out this example of normal progress bar animations: JSFiddle Alternatively, here is an example with the `onload` loader added: JSF ...

Encountering an issue when attempting to construct the project: it asks for callback functions, but instead received an [

I'm currently facing an issue while trying to access a function that is crucial for updating some database values. Whenever I attempt to build the project, I encounter the following error: Error: Route.post() requires callback functions but got a [ ...

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...

Incorporating a fresh attribute into a javascript object

We start with an array that includes the following data structure: array = [{ key: '2001', values: [ { id : '123a', points: 3, hours: 3 }, { id : '123a', points: 4, hours: 2 }, { id : '4444', points: 3, hour ...