Navigating JSON data along diverging paths

Greetings everyone,

I am interested in creating a unique JSON script that has the capability for objects to either retrieve a value or navigate through a data path.

For instance:

{
  "A" : {
    "B" : "123"
  }
}

In the given example, when I access the value of A.B, it returns 123. However, I also want A to possess its own distinct value, such as "XYZ".

Therefore, when I inquire about what A is, it should return "XYZ", and if I ask about A.B, it should return "123".

I hope this explanation is clear; typically, JSON operates on a singular path, yet I desire the ability to traverse the path and allocate values to individual nodes. It's akin to each node having both a value and relationships with children and parents.

Any insights into this concept would be highly appreciated.

Answer №1

You have the ability to create a custom function by utilizing the reduce() method in order to pass nested keys as a string.

const data = {"A": {"B": "123"}}

const getPath = (path, obj) => {
  return path.split('.').reduce(function(r, e, i, arr) {
    return r[e] || (arr[i + 1] ? {} : undefined)
  }, obj)
}

console.log(getPath('A.B', data))
console.log(getPath('A', data))
console.log(getPath('A.C', data))

If your intention is to always retrieve the last found value in the path, you can opt for this alternative approach.

const data = {
  "A": {
    "B": "123",
    "C": {"D": 2}
  }
}

const getPath = (path, obj) => {
  return path.split('.').reduce((r, e) => (r[e] || r ), obj)
}

console.log(getPath('A.B', data))
console.log(getPath('A.C.F.G', data))
console.log(getPath('A.B.Q', data))

Answer №2

It is not possible to assign two different values to the same object property. However, you can achieve a similar functionality by structuring your code like this:

{
  "A" : {
    "B" : "123",
    "value" : "XYZ"
  }
}

Accessing A.value will return XYZ and A.B will return 123

Edit:

If you define A as a function that returns the desired value, you can then add properties to A. Nevertheless, it is generally considered bad practice:

let A = function () {
  return 'XYZ';
}

A.B = '123';

let obj = {
  A
};

console.log(A()); // XYZ
console.log(A.B); // 123

Answer №3

JSON is short for JavaScript Object Notation, which means that JSON represents an object in JavaScript. Each attribute of an object can only have one value. Here's an example:

var obj = { "key1": { "nestedKey": "value"}

This creates an object like { key1: { nestedKey: value}. So, when you access the values, it would look like this:

console.log(obj.key1) // {nestedKey: value}
console.log(obj.key1.nestedKey) // value

Unfortunately, trying to assign multiple values to a single attribute is not feasible in JSON.

https://www.w3schools.com/js/js_json_intro.asp

Answer №4

It appears there may be some confusion regarding the issue at hand. It is essential to determine the proper logic for obtaining the JSON string before making the request or processing the response. Implementing multiple diverging logical paths could lead to potential complications and should be avoided.

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

Developing an interactive form for instant price calculations

I'm currently tackling a project that involves developing an order form capable of computing the price of a door in real-time. However, I am having trouble deciding on the best approach to take. The form will include the following inputs: Frame (Dr ...

How do I store Data along with the Heading name into my local storage using Query and Json?

$(document).ready(function () { $(":button").click(function () { var btn = $(":button").val(); if (btn == 'Favoritisieren') ...

Ways to determine the types of props received by a function when the arguments vary for each scenario?

I have a specialized component that handles the majority of tasks for a specific operation. This component needs to invoke the onSubmit function received through props, depending on the type of the calling component. Below is an example code snippet show ...

Unable to cut a line shape in Three.js using THREE.ExtrudeGeometry for punching

Hey everyone, I'm brand new to Three.js I'm looking to cut out some shapes from a flat board using THREE.ExtrudeGeometry. Check out the code snippet below: // Code snippet here... In my example, I've included a circular shape and t ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

Retrieve the folder and file name selected by the user in the browser

Can the client's directory path be obtained for a file uploaded to a server? ...

"Streamlining communication: Building a mail sending form with AJAX, JQuery

I am currently dealing with a dilemma on my website where I have 2 contact forms, and I am utilizing ajax jQuery to send emails via PHP. Everything works smoothly when I use a single form along with jQuery. However, when I try to adapt the jQuery code for ...

Issue with CollectionView not displaying images after JSON parsing

As a newcomer to iOS Development, I am trying to parse images from web services and display them in custom cells within a collection view. Here is the code I have written: #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0) #defi ...

Check the vuelidate required function in Vye.js for ensuring that all necessary fields

I am currently utilizing the vuelidate plugin for form validation. import { required, maxLength } from 'vuelidate/lib/validators'; In my Vue component, I have a method called isFinishedFill(): methods: { isFinishedFill() { return !!this. ...

Checking a condition with a for loop in Javascript

I'm working on developing a function that can generate a random number between 0 and 9 that is not already included in an array. Here is the code I have come up with so far: var myArr = [0,2,3,4]; console.log("Array: " + myArr); function newN ...

Using Javascript to make a nested JSON api request that includes several query parameters

I am currently working on creating an API for my upcoming website, but I am facing difficulty in obtaining multiple query results using the same URL in an express app. Sample data: var data = [{ articles : [{ id : '0', url : ...

Steps to showcase a HTML modal based on the outcome of a JavaScript/AJAX database query

Currently in the process of developing a Facebook game utilizing html and Javascript. With two modals on an html page (referred to as ModalA and ModalB), the goal is to link both modals to a single button, triggering the display of only one modal based on ...

Having difficulty extracting information from a Json string stored in the SQL Server database

I need to extract the fileDisplayNames from a specific data set column that contains JSON strings. select id_ref id, JSON_VALUE(cast(data_map as varchar(max)),'$.dataMap."4805".fileDisplayName') Attachments, data_map dataa from action_data wher ...

Oppose the idea of splitting KeyValue Pair collections into individual objects

I am currently faced with a challenge where I must convert any object into a key-value pair format. So far, my method has been successful for simple classes as well as those that contain other classes within them. For example, consider the following: pu ...

Utilize JQuery to Extract JSON Data from Django

How can I properly transfer data results from Django to JavaScript in JSON using an AJAX call? In Django, I currently have the following variable: results = {key1:[1,2,3], key2:[[name1,lat1,lng1],[name2,lat2,lng2],[name3,lat3,lng3]]} After suc ...

Troubleshooting: Vue 3 Vite encountering 404 error when attempting to load fonts from assets using Font Loading API

Attempting to dynamically load fonts from the assets directory within Vue 3 (Typescript) using Vite has led to a 404 error occurring. https://i.sstatic.net/H3Ho7.png const fonts = import.meta.glob('@/assets/fonts/*.otf') console.log(fonts) asy ...

Attaching a JavaScript-infused text to innerHTML within a template

In a Windows 8 metro style app, I am working with a list of articles that are passed to a Flip View Control. Each article contains a description text in HTML which includes JavaScript. I understand the need to use the `MSApp.execUnsafeLocalFunction` functi ...

Is a Toolbar plugin or custom Toolbar options the better choice for your project?

Could anyone recommend a Jquery plugin for adding a ToolBar option to my web application? I've searched and researched for the past 48 hours but haven't found a reliable one yet. If the recommended toolbar resembles the image below, that would b ...

Display a random div element in jQuery without specifying a specific class

I have a dynamic list that I am displaying in a div as shown below <div class="cards card1"> <div class="front"> <p>Front 1</p> </div> <div class="back1" style="display: none"> <p>Back 1</p> ...

Query SQL Server database to retrieve column values that match a specific pattern

I have a SQL table named details, and I am attempting to extract specific data from the Content column. The content in this column is structured as follows: Id Content --------------------------------------------------------------------------- X345 ...