Extract the value of a key from a particular object in a JSON array using JavaScript

I have a JSON structure that looks like this:

{
map: [
      {"key1":"valueA1", "key2":"valueA2", "key3":"valueA3"},
      {"key1":"valueB1", "key2":"valueB2", "key3":"valueB3"},
      {"key1":"valueC1", "key2":"valueC2", "key3":"valueC3"},
       .... and so on
     ]
}

When I load this into my JavaScript application using JSON.parse(), I want to be able to retrieve the value of key3 from the object in the array where key2='valueB2'.

I currently achieve this by looping through the array, but I'm wondering if there is a more elegant and efficient way to do this without knowing the index number of the array element.

I've searched extensively online for solutions, but with little success. Would it be better for me to simplify or remove the array altogether and use a list of objects instead?

Thank you!

Answer №1

JSON typically uses double quotes " for keys and values, except when dealing with numbers.

While there are new functional array iteration methods available on modern JS engines and browsers, using a loop remains the most efficient and reliable choice. You can explore these new methods here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

If you have the flexibility to modify the JSON structure, consider transforming it into an Object instead of an array of objects, where the key corresponds to the value of key2 and the value is the Object itself.

For example:

{
    "valueB2": {
        "key1": "valueB1",
        "key2": "valueB2",
        "key3": "valueB3"
    }
}

This way, retrieving the object would be as simple as O(1) and done by just calling obj["valueB2"]

Answer №2

There's no simpler alternative to achieve this task. The only information available without iteration are the indexes. Unfortunately, those aren't the identifiers you're looking for, so you'll have to scrutinize the content by using a loop:

function findByKey(array, keyToFind) {
  for (let index = 0; index < array.length; index++) {
    if (array[index].key === keyToFind) {
      return array[index];
    }
  }
}

You could consider implementing something along those lines.

Answer №3

In combining elements from both responses, I have implemented a more streamlined JSON format:

[
    {"key1":"valueA1", "key2":"valueA2", "key3":"valueA3"},
    {"key1":"valueB1", "key2":"valueB2", "key3":"valueB3"},
    {"key1":"valueC1", "key2":"valueC2", "key3":"valueC3"},
    .... and so on
]

By using the recommended loop function to locate the element with "key2:"valueB2", I can efficiently access the array primarily by index, only resorting to the loop-search when necessary. This approach struck me as a well-balanced solution. Additionally, I came to realize that the intermediate object "map" was redundant and eliminated it from my structure.

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

Importing modules dynamically in NextJS allows for the loading of

I have a basic function that is responsible for loading a script: const creditCardScript = ( onReadyCB, onErrorCB, ) => { let script = document.createElement("script"); script.type = "text/javascript"; script.src = process.CREDIT_CARD_SCRIPT; ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...

Is it possible to modify a portion of the zod schema object according to the value of a

My form consists of several fields and a switch component that toggles the visibility of certain parts of the form, as shown below: <Field name="field1" value={value1} /> <Field name="field2" value={value2} /> &l ...

Decoding JSON with Groovy in Jenkins

I have a JSON object with different environments like dev, stage, master, and updates along with their corresponding details such as hoster, id, merge, and slackChannel. { "dev": { "hoster": "123", "id": "123", }, "stage": { "hoster": "1 ...

Insert a new, unique div onto an HTML webpage using JavaScript, ensuring no duplicates are created

Having an issue with this code snippet where nothing is being added. It seems like the variable result may not be taking a number or something else, but I'm not entirely sure why. $(document).ready(function () //document.getElementById(1).style. ...

The loop termination condition is malfunctioning - C

I'm currently working on a homework assignment that involves dynamic arrays, so I decided to experiment with some basic programs to help me understand how they work. #include <stdio.h> #include <string.h> #include <stdlib.h> int m ...

Accessing variables from child controllers with populated select inputs in Angular

I'm currently facing an issue involving 3 controllers: Parent Controller: DocumentController Child Controller1: XdataController Child Controller2: CompanyController The child controllers are used to populate data in three Selector inputs on the fron ...

Is it possible for Yarn to fail to include both ESM and CJS versions of a package during publishing or adding?

Our application is equipped with Parcel and utilizes a UI library consisting of react components. This UI library is built with Rollup and is privately published on NPM. I've been attempting to transition our application to Parcel 2, but I'm fac ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Child component in Vue 2 not receiving defined props

After numerous attempts, I am still struggling to successfully pass a prop down to a child component. <Project :grossMarginPerResource="grossMarginPerResource" :threshold="threshold" :orderBy="orderBy" @refetch="refetc ...

Encountered an error while compiling the ./src/App.js file - Module could not

Encountering a challenge while attempting to run my system on the local server. After running npm install, followed by npm run start, I encountered the following error: Failed to compile ./src/app/App.js Module not found: Can't resolve 'assets/ ...

Retrieve the value of the object within the mysterious index loop in JavaScript

I have retrieved search results from the data, and each time the index of my search result varies. At one point, the result may appear in the 4th index, while at another time it might be in the 100th index. How can I retrieve the rank value from within t ...

What causes useEffect to be triggered multiple times, even when it is dependent on another useEffect function that is being executed repeatedly?

I have a specific requirement that involves using two useEffect hooks. First useEffect is used to set the latitude and longitude in the state with an empty dependency array. useEffect(() => { navigator.geolocation.getCurrentPosition(geo = ...

Troubleshooting: Why the TableTools basic usage example is not functioning as

After replicating the code from http://datatables.net/release-datatables/extensions/TableTools/examples/simple.html in my Visual Studio project, I organized the files by saving two css files as style1.css and style2.css, along with three js files named sc ...

What is the proper way to transmit JSON data to a node.js server using the fetch API in JavaScript

I am currently working with a node.js back-end server and Angular 10 on the front-end. I need to pass data from the front-end to the back-end using fetch. This is my front-end code: testmariadb($event: MouseEvent) { return fetch('/api/customQuery ...

Tips for positioning the labels in a sankey diagram for optimal alignment

When multiple values are the same in this scenario, such as 0, the labels start to overlap. Can anyone provide guidance on how to align these labels vertically? Ideally, I would like them to be positioned at the top of the node/bar. Highcharts.chart(&apos ...

Is the Android Webview causing input boxes to double up?

Looking to develop an Android application that utilizes a webview for users to input their username/password, but encountering a strange issue where tapping on the input boxes creates duplicates (as shown in the image below). I have implemented the iScroll ...

Unique Soundcloud visualization using webglonDeletegist

After going through the SoundCloud documentation, I have been trying to figure out how to create a visualizer for SoundCloud tracks. The challenge is that in order to achieve this effectively, I need access to the source waveform. I suspect that direct acc ...

Navigate to a specific section of a webpage with automatic scrolling

I'm developing a Chrome App and incorporating the web view tag, which functions similarly to an iframe. Is there a way to load a webpage inside the web view halfway down the page? I have attempted the following: application.js: $(document).ready(f ...

Vue alert: A duplicate key with the value of '10' has been identified. This could potentially lead to an issue with updates

I've been encountering a persistent error that I can't seem to resolve: [Vue warn]: Duplicate keys detected: '10'. This issue is causing an update error in my application. Despite trying the following steps, the error continues to appe ...