How can I retrieve the top-level key based on a value within a JSON object nested in JavaScript?

If I have the value Africola for key name in the following nested JSON structure, how can I retrieve its corresponding upper-level key 'barID1' using JavaScript?

{
  "barID1": {
    "address": "4 East Terrace, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
    "description": “description text”,
    "imgURLs": [ "Https:url1”,  "https:url2”, "https:url3” ],
    "lat": -34.810585,
    "lon": 138.616739,
    "name": "Africola",
    "phone": "(08) 8223 3885",
    "status": "active",
    "venueImgURL": "https:url”
  },
  "barID2": {
    "address": "138/140 Gouger St, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
     "description": “description text”,
    "imgURLs": [ "Https:url1”,  "https:url2”, "https:url3” ],
    "lat": -34.848082,
    "lon": 138.599813,
    "name": "Disco Mexico Taqueria",
    "phone": "0416 855 108",
    "status": "active",
    "venueImgURL": "https:url”
  }
}

Answer №1

Your JSON data contained invalid characters which caused it to be malformed. Try using the find method on keys

let obj = {
  "barID1": {
    "address": "4 East Terrace, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
    "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.810585,
    "lon": 138.616739,
    "name": "Africola",
    "phone": "(08) 8223 3885",
    "status": "active",
    "venueImgURL": "https:url"
  },
  "barID2": {
    "address": "138/140 Gouger St, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
     "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.848082,
    "lon": 138.599813,
    "name": "Disco Mexico Taqueria",
    "phone": "0416 855 108",
    "status": "active",
    "venueImgURL": "https:url"
  }
};

let result = Object.keys(obj).find(key => obj[key].name === "Africola");
console.log(result);

Converted into a function:

let obj = {
  "barID1": {
    "address": "4 East Terrace, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
    "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.810585,
    "lon": 138.616739,
    "name": "Africola",
    "phone": "(08) 8223 3885",
    "status": "active",
    "venueImgURL": "https:url"
  },
  "barID2": {
    "address": "138/140 Gouger St, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
     "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.848082,
    "lon": 138.599813,
    "name": "Disco Mexico Taqueria",
    "phone": "0416 855 108",
    "status": "active",
    "venueImgURL": "https:url"
  }
};

const findKeyByName = (obj, search) => Object.keys(obj).find(key => obj[key].name === search);

console.log(findKeyByName(obj, 'Africola'));
console.log(findKeyByName(obj,'Disco Mexico Taqueria'));

Answer №2

To efficiently find a specific value in an object, you can combine the use of Object.entries() with Array.find(). Here is an example:

const input = {
  "barID1": {
    "address": "4 East Terrace, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
    "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.810585,
    "lon": 138.616739,
    "name": "Africola",
    "phone": "(08) 8223 3885",
    "status": "active",
    "venueImgURL": "https:url"
  },
  "barID2": {
    "address": "138/140 Gouger St, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
     "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.848082,
    "lon": 138.599813,
    "name": "Disco Mexico Taqueria",
    "phone": "0416 855 108",
    "status": "active",
    "venueImgURL": "https:url"
  }
};

let [key, val] = Object.entries(input).find(
    ([k, v]) => v.name === "Africola"
);

console.log("key is :", key);
console.log("value is :", val);

Answer №3

To solve this problem, I recommend using the Object.entries() and Array.find() methods.

const data = {
  "barID1": {
    "address": "4 East Terrace, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
    "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.810585,
    "lon": 138.616739,
    "name": "Africola",
    "phone": "(08) 8223 3885",
    "status": "active",
    "venueImgURL": "https:url"
  },
  "barID2": {
    "address": "138/140 Gouger St, Sydney NSW 2000",
    "appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
     "description": "description text",
    "imgURLs": [ "Https:url1",  "https:url2", "https:url3" ],
    "lat": -34.848082,
    "lon": 138.599813,
    "name": "Disco Mexico Taqueria",
    "phone": "0416 855 108",
    "status": "active",
    "venueImgURL": "https:url"
  }
};

const [key, obj] = Object.entries(data).find(([key, obj]) => {
  return obj.name === 'Africola';
});

console.log(key, obj);

You can view a working example on Fiddle: https://jsfiddle.net/zty6fgcp/

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 correct way to use fitBounds and getBounds functions in react-leaflet?

I'm struggling with calling the fitBounds() function on my Leaflet map. My goal is to show multiple markers on the map and adjust the view accordingly (zoom in, zoom out, fly to, etc.). I came across an example on How do you call fitBounds() when usi ...

Guide on extracting the text from the <script> tag using python

I'm attempting to extract the script element content from a generic website using Selenium. <script>...</script> . url = 'https://unminify.com/' browser.get(url) elements = browser.find_elements_by_xpath('/html/body/script[ ...

"Any ideas on resolving the unexpected JSON exception org.json. Ran into an index out of range issue. Suggestions

Can someone assist me with resolving this error? I have 43 items in my ListView, but why am I encountering index 4338? I tried the solution provided here: JSONArray Exception : Index 50 out of range [0..50). Is there any limit on JsonArray. Despite making ...

Step-by-step guide to retrieve JSON data from VARCHAR field in Snowflake

I am working with a VARCHAR column that stores JSON data. Here's an example row: { "id": null, "ci": null, "mr": null, "meta_data": { "product": { "product_id": "123xyz", "sales": ...

"I'm encountering an issue with Passport.js where req.isAuthenticated is throwing an error as not

Recently I started working with node and express, along with passport.js for building an authentication feature. However, I encountered an issue while using a middleware function called "checkNotAuthenticated" in my routes. The error message I received was ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

The JsonLayout in Nlog lacks support for LogEvent Properties

I attempted to follow the example provided at https://github.com/nlog/nlog/wiki/JsonLayout#nested-json-with-structured-logging but in my case, the output does not contain any data in the eventProperties field. NLog configuration: <?xml version=" ...

What are the best practices for using .toString() safely?

Is it necessary for the value to return toString() in order to call value.toString()? How can you determine when you are able to call value.toString()? <script> var customList = function(val, lst) { return { value: val, tail: lst, t ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

Encountering difficulties in accessing state while utilizing async callback functions in React.js

After finding this function on Stack Overflow, I decided to use it in order to update a database and profile information immediately after a user signs up. The function is working as expected, but I am encountering an issue where I can no longer access the ...

Turning a stateful React component into a stateless functional component: Ways to achieve functionality similar to "componentDidMount"

I recently developed a small, stateful React component that utilizes Kendo UI to display its content in a popup window when it loads. Here is a snippet of the code: export class ErrorDialog extends React.Component { constructor(props, context) { sup ...

Customizing functions in JavaScript with constructor property

What is the best way to implement method overriding in JavaScript that is both effective and cross-browser compatible? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

Preserve specific values within the nested structure of a JSON object

I am currently leveraging Python within AWS services. Within my possession is a substantial JSON object: {'TextDetections': [{'DetectedText': 'AR', 'Type': 'LINE', 'Id': 0, 'Confidence' ...

Instructions on transferring an image to a server. The image is located on the client side within an <img> tag

Looking for an effective way to upload an image when the type is “file”? The goal here is to send an image from an image tag to the server without converting it into base64 due to size constraints. <form id="form-url"> <image src ...

Retrieving substantial amounts of data from JSON stream

I am in need of working with a JSON stream that contains large blobs of data (although the number of nodes is relatively low), like this example: { "meta": { "status": "ok" }, "items": [ { "name": "name of item 1", "data": "The d ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

Incorporate multiple array values within an if statement

Looking to dynamically change the background image of an element based on specific strings in the URL. Rather than changing it for each individual term like "Site1", I want to be able to target multiple words. Here's what I've tried: var urlstri ...