What is the best way to verify that a JSON key contains only distinct values within a JSON document using JavaScript?

I'm working with a JSON file structure that looks something like this:

"fields": {
"asset": {
    "values": [{
            "asset": {
                "id": "Info_text",
                "type": "text",
                "value": "ABCD"
            }
        }, 
        {
            "asset": {
            "id": "Info_input",
            "type": "input",
            "value": "ABCDE"
            }
        }
    ]
}
}

My task is to write JavaScript code that will iterate over the values of the "id" field and check if they are unique. Can someone help me figure out how to achieve this?

Answer №1

Check out this demonstration that doesn't require any additional libraries. It shows how you can determine if a key/value pair is unique in a JSON object and find the number of occurrences:

var jsonData = {
  "fields": [
    {
      "asset": {
        "id": "Info_input",
        "values": [
          {
            "asset": {
              "id": "Info_text",
              "type": "text",
              "value": "ABCD"
            }
          },
          {
            "asset": {
              "id": "Info_input",
              "type": "input",
              "value": "ABCDE"
            }
          },
          {
            "asset": {
              "id": "Info_input",
              "type": "input",
              "value": "ABCDE"
            }
          }
        ]
      }
    }
  ]
}

function countKeyValue(key, value, obj) {
var total = 0;
var keys = Object.keys(obj);
keys.forEach(function(k) {
var v = obj[k];
if(typeof v === 'object') {
total += countKeyValue(key, value, v)
}
else if(k === key && v === value) {
total += 1;
}
});
return total;
}

function checkUniqueness(key, value, obj) {
return countKeyValue(key, value, obj) === 1;
}


console.log(countKeyValue('id', 'Info_text', jsonData));
// -> 1

console.log(countKeyValue('id', 'Info_input', jsonData));
// -> 3

console.log(countKeyValue('value', 'ABCDE', jsonData));
// -> 2

console.log(countKeyValue('xxx', 'yyy', jsonData));
// -> 0

console.log(checkUniqueness('id', 'Info_input', jsonData));
// -> false

console.log(checkUniqueness('id', 'Info_text', jsonData));
// -> true

Enjoy exploring!

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

Leverage jQuery/JS to divide a lone <ul> element into four distinct <ul> lists

I'm working with a dynamically generated single list (<ul>) that can have anywhere between 8 and 25 items (<li>'s). Here's an example of the HTML structure: <ul id="genList"> <li>one</li> <li>two</l ...

Insert a new row into the table using jQuery right above the button

I am working on a table where I need to dynamically add rows in the same rowId upon clicking a specific button. For instance, when the "Add Row 1" button is clicked, a new row should be added under "Some content 1", and so on for other rows. <table i ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

What should we name this particular style of navigation tab menu?

What is the name of this tab menu that includes options for next and previous buttons? Additionally, is there a material-ui component available for it? https://i.sstatic.net/0m9rH.png ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

Injecting windows in Angular

Is there a way to prevent the Angular instance from injecting into the global (window) scope when required and bundled with webpack or any other module bundler? Upon inspection, I discovered that the current main Javascript file in the Angular npm package ...

Configure the IIS HttpCompression settings to compress only JSON responses, specifically those coming from asynchronous JavaScript and

I've been tinkering with the "applicationHost.config" file located in the directory "C:\Windows\System32\inetsrv\config." Everything seems to be going smoothly, but I just want to confirm something: <httpCompression directory=" ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

Ionic: Error - Unable to access the 'ready' property of an undefined object

I keep encountering this error message: TypeError: Cannot read property 'ready' of undefined Here is the snippet of my code: angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.dir ...

Having trouble with jQuery modal not adjusting its height properly

I am a jquery modal popup newcomer. I can open the modal when clicking on the hyperlink, but I'm having trouble with the height setting. Despite my attempts and searches online, I couldn't figure it out. When trying to post a question about the & ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

Retrieving event.data from the input handler on a textarea element

I've spent the past few days researching this issue. Here's some context to help explain the goal: I have a textarea and I want it to detect special characters (like @) that I define as part of a dictionary. It should then display an autocomple ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

Add a user to a guild using Discord API

Hello, I'm currently working on integrating the Discord API to automatically add users to a guild upon login. However, I keep encountering a 401 Unauthorized error and I'm unsure of the reason behind it. Below is a snippet of my code: const data ...

Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping. I tried solving it with margins and paddings but believe there must be a simpl ...

Styling an active link in Next.js using Styled Components

Looking for a way to customize the active link style using styled components. I have a navigation bar where the currently active link should have a specific style applied. Any suggestions are appreciated! import React from 'react' import Link f ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet. Here is the HTML CODE snippet: <!DOCTYPE HTML> < ...

Is it possible to include an if or else condition in jQuery JSON response?

I have an issue with adding my Jquery JSON response to a data table. However, I need to implement if conditions based on the day. Can you provide me with an example of how to do this? Specifically, I need to use conditions in the data.hours.day field. Th ...

Starting jQuery on embedded websites

I developed a platform that relies on JavaScript. Users of my platform are required to paste a code similar to Google Analytics, which automatically deploys a custom set of JavaScript functions along with the latest jQuery 1.9 through Google. The issue I ...