When a word is found in the key of an object

Here is an example of the object I am working with:

{"status":200, 
"success":true, 
"result": [ {"Description":"", "Year":"", "Price/STK":"", "Main Cat":"Fruits"} ]
}

I have multiple lists that I need to make use of, and the Price key can take different forms such as Price/STK, Price/Box, Price/Btl or just Price.

Instead of checking each key individually, I want to be able to search for a price-related key and extract its value.

Is there a way to determine if a word like 'Price*' is present in a key and retrieve that value?

Answer №1

If you're looking to search for a specific key in an object, there is no direct method to do so. Instead, you will need to iterate through the keys and check each one individually.

An approach you could take is to create a custom function that simplifies this process:

function findKey(objectToSearch, keyToFind) {
    for (var k in objectToSearch) {
        if ( k.toLowerCase().indexOf(keyToFind.toLowerCase()) !== -1) 
            return objectToSearch[k];
    }
    return null;
}

findKey({year : 2015, "Price/STK" : "value"}, "price"); // returns "value"

Check out the example on JSFiddle

Answer №2

An efficient solution to this issue can be achieved with the help of lodash (or underscore) library.

_.findKey(obj, function(key) { return _.startsWith(key, 'Price')})

This code snippet locates the initial key that commences with the word "Price".

Answer №3

To retrieve the names of properties from an object, you can utilize Object.keys and then employ indexOf to look for a specific value. However, keep in mind that indexOf only performs an exact match and does not accept regular expressions as an argument.

As a workaround, you may need to iterate through all the property names until you identify the desired one. Fortunately, there are built-in iterators that can assist in this process:

var exampleObject = {"status":200, 
  "success":true, 
  "result": [ {"Description":"desc", 
               "Year":"yr", 
               "Price/STK":"price/stk",
               "Main   Cat":"Fruits"}
            ]
};

function findValueLike(obj, property){
  var regex = new RegExp('^' + property);
  var targetValue;
  Object.keys(obj).some(function(prop) {
    if (regex.test(prop)) {
      targetValue = obj[prop];
      return true;
    }
  });
  return targetValue;
}

document.write(findValueLike(exampleObject.result[0], 'Price')); // price/stk

Another approach that utilizes indexOf on the property name may offer improved speed and requires less code:

function findValueLike(obj, property){
  var targetValue;
  Object.keys(obj).some(function(key) {
    if (key.indexOf(property) == 0) {
      targetValue = obj[key];
      return true;
    }
  });
  return targetValue;
}

This can be further simplified to:

function findValueLike(obj, property, value){
  Object.keys(obj).some(function(key) {return key.indexOf(property) == 0 && ((value = obj[key]) || true)});
  return value;
}

While this last implementation allows for a default value to be specified for value, it may appear overly complex to some users.

Alternatively, you can utilize an arrow function:

function findValueLike(obj, property, value){
  Object.keys(obj).some(key => key.indexOf(property) == 0 && ((value = obj[key]) || true));
  return value;
}

Answer №4

Identify and extract the "Price" key from the object within the result array, and then retrieve the corresponding value. Below is a sample function that demonstrates this process.

function getSalePrice(obj){
  return obj.result[0][
      Object.keys(obj.result[0]).filter(function(el){ 
          return el.indexOf("Price") > -1 
      })[0]
  ]
}

var productData = {"status":200, 
"success":true, 
"result": [ {"ProductID":"123", "Name":"Apple", "Price/Unit":"5.99", "Category":"Fruits"} ]
};

document.write(getSalePrice(productData));

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

What is the best way to turn my thumbnail into a clickable link while having the title positioned to the right?

Is there a way to create a thumbnail that acts as a link and position the title next to the thumbnail? I have experimented with using 'after' and modifying the HTML structure to align them horizontally. Any ideas on how I can achieve this layou ...

Determine the frequency values and coordinates of the normal distribution curve (X and Y axes)

I have successfully implemented the Histogram chart using react-plotlyjs. The graph is working fine but now I need to draw the normal distribution curve using X and Y axes. While I have the coordinates for the X axis, the Y axis values are automatically ca ...

Is there a way to locate an element within innerHTML using getElementById?

Is it possible to achieve the following code snippet? <div id="parent"> <iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe> </div> v ...

What is the best method for extracting attribute values from multiple child elements using puppeteer?

When using this code, I can retrieve the attribute value of the first element selected. By adding /html/body/section/div[3]/img<2> or img<3> in the xpath, I am able to retrieve data for subsequent img elements. However, the parent element on t ...

"Integrating JavaScript in C# Code Behind: A Step-by-Step Guide

Is there a way to trigger this javascript function using C# code in the backend when the page loads? Your assistance is greatly appreciated, thank you. <script type="text/javascript"> document.onkeydown = function (event) { event = ( ...

Issue encountered: Incompatibility between Mongoose Populate and Array.push()

After reading a different post addressing the same issue, I still couldn't figure out how to implement the solution into my own scenario. The discussion revolved around the topic of node js Array.push() not working using mongoose. In my Mongoose asyn ...

Shifting Directive Logic to a Method within a Vue Component

I am currently working with a VueJS component that utilizes the style attribute in the following way: <section :style="{ backgroundImage: src && 'url(' + src + ')' }"> ... <script> export default { props: [& ...

Store JWT as a cookie in Vue JavaScript and ensure it is successfully saved before proceeding

Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home. However, there seems to be an issue with the authentication check on the /home route. When c ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...

Learn the steps for assigning a distribution tag to an npm package within a private registry

Operating with my own exclusive Gemfury repository, I am actively releasing npm packages. Intrigued by the prospect of applying distribution tags to my packages (as per this guide: https://docs.npmjs.com/cli/dist-tag). The configuration of my npm registr ...

What is the best method for creating a loop script within a widget using script?

I am trying to implement a loop within a widget, however, the widget contains an internal script: <!DOCTYPE html> <html><head></head><body> <script> list=["AMAR3","BBDC4", "BEEF3", "BPAN4", "BRFS3", "B3SA3", "CVCB3" ...

The link appears to be broken when trying to access the notFound component in Next.js version 13

In my Next.js 13.4 app directory, I added a not-found.tsx component that functions correctly when entering the wrong route: import Link from 'next/link' function NotFound() { return ( <section> 404, page not found ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

Issue with displaying Git remote repository on list item element (ul) not appearing

My attempt to showcase my GitHub repositories via their API is not displaying on my webpage, even though the exact same code works perfectly fine here on JSFiddle Upon debugging, it seems that the script is being invoked but the content is not loading wit ...

Discover the most recent date of a document by analyzing two distinct fields: the month and the year

In my mongoDB database, the documents have the following structure: {username:String, paymentYear:Int, paymentMonth:Int} I am trying to retrieve the latest document for a specific username, which would be the one with the date closest to the current Date ...

What could be the reason for my jQuery focusout (or blur) event failing to trigger?

On the jsfiddle link provided, the HTML code at the end section looks like this: <input type="text" id="BLAboxPaymentAmount" value="2"> </br> <input type="text" id="BLAboxSection5Total" value="3"> Below that is the jQuery code snippet: ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

How to obtain the full path of a file downloaded using a Chrome extension

Currently in the process of creating a chrome extension that has the functionality to download specific files from various webpages. For this purpose, I have designed a popup.html where users can input the desired name for the file to be downloaded. Additi ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...