JavaScript: Locate a property and its corresponding value within a JSON object

Dealing with a JSON object that varies in structure, but always contains a key. Any suggestions on how to extract this information?

For example:

"Records": {
    "key": "112"
}

Or

"Records": { 
    "test": {
        "key": "512"
    }
}

Or even within an array:

"Records": { 
    "test": {
        "test2": [
            {
                "key": "334"
            }
        ]
    }
}

I've tried multiple approaches, but still haven't found a solution.

Answer №1

I won't provide the exact code, but I can give you a hint that might be helpful. Start by converting a JSON object to a string using

JSON.stringify(obj);

After that, use the indexOf() method to search for a key. Extract the strings between the previous '{' and next '}' characters, then convert them back into a JSON object by using

var obj =  JSON.parse(string);

Finally,

 var value = obj.key

Answer №2

Perhaps this could be a solution (assuming the key is always a string and you are not concerned about the rest of the data)

const data = [`"Records": { 
    "test": {
        "test2": [
            {
                "key": "334",
                "key": "3343"
            }
        ]
    }
}`, `"Records": { 
    "test": {
        "key": "512"
    }
}`, `"Records": {
    "key": "112"
}`]

const getKeys = data => {
  const keys = []
  const regex = /"key"\s*:\s*"(.*)"/g
  let temp
  while(temp = regex.exec(data)){
    keys.push(temp[1])
  }
  return keys
}

for(let json of data){
  console.log(getKeys(json))
}

Answer №3

What is the best way to obtain it?

You can achieve this through recursion! For example:

function fetchValue(data) {
    if (data.value) return data.value;

    return fetchValue(data[Object.keys(data)[0]]);
}

https://example.com/randomstring/

Answer №4

An iterative and recursive method can be employed to retrieve the object containing a specific key.

function getReferenceByKey(obj) {
    function find(obj) {
        if (!obj || typeof obj !== 'object') {
            return;
        }
        if ('key' in obj) {
	    ref = obj;
	    return true;
	}
	Object.keys(obj).some(function (k) {
	    	return find(obj[k]);
	});
    }
    
    var ref;
    find(obj);
    return ref;
}

var obj1 = { Records: { key: "112" } },
    obj2 = { Records: { test: { key: "512" } } },
    obj3 = { Records: { test: { test2: [{ key: "334" }] } };

console.log(getReferenceByKey(obj1));
console.log(getReferenceByKey(obj2));
console.log(getReferenceByKey(obj3));

Answer №5

If you want to give this a shot

const values = {
"Items": {
"type": "123"
}
};

const values2 = {
"Items": {
"check": { "type": "456" }
}
};

const values3 = {
"Items": {
"check": {
"nestedValues": [
{ "type": "789" },
]
}
}
};

function findType(object, typeToFind = 'type') {
return Object.keys(object).reduce((finalObject, objectKey) => {
if (objectKey !== typeToFind) {
return findType(object[objectKey]);
} else {
return finalObject = object[objectKey];
}

}, [])
}

const result = findType(values);
const result2 = findType(values2);
const result3 = findType(values3);
console.log(result);
console.log(result2);
console.log(result3);

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

Error: Security Exception raised when making nested ajax requests

Here's a problem I'm facing. I've been using an ajax call in JavaScript/jQuery to extract Gmail contacts like so: function getUserInfo() { var xml_parse = ""; $.ajax({ url: SCOPE + '?max-results=9999&access_token=' + a ...

vite.config.js failed to be loaded due to an error

Following the Vue docs, I decided to create a new Vue app using these steps: npm init vue@latest npm install After setting everything up, I attempted to run npm run dev, but encountered an issue. https://i.sstatic.net/Q22IX.png Here are my environments ...

Sophisticated method for implementing dynamic components with props in Vue

In a specific scenario, I am using an API to output all the content for my Page, including its structure. To provide context, imagine a CMS with a page builder feature where authors can place components via drag and drop to create pages, which are then del ...

Guide to seamlessly integrating form data into MySQL using JavaScript and HTML without redirecting the user from the current page

Having trouble inserting a new user into MySQL database? I've attempted using both jQuery and pure JavaScript, but it doesn't seem to be working. There's no response when I click on the submit button. Any ideas on what might be causing this ...

Utilizing JSON for the setAttribute() method

While I've made progress on this issue, I've encountered numerous confusing methods. The goal is to utilize the key:value pairs in attr{} for the setAttribute() function without relying on any framework. If anyone could provide a straightforward ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...

Guide on obtaining JSON response following file upload using ActionScript

I am proficient in uploading files using action script. To learn more about uploading a zip file using HTTP POST with actionscript 3.0, please visit this link. Here is the code snippet: var urlRequest:URLRequest = new URLRequest(PUBLISH_ZIP_FILE_URL); / ...

Filtering a Django queryset by ID and returning it as a JsonResponse

My goal is to extract the ID and create a filtered queryset based on that ID. Here's an example code snippet: views.py class MyProfile(TemplateView): model = Reports template_name = 'template.html' def get_context_data(request, *args, **kw ...

Preventing the detection of a jshint "error"

When creating an object using the constructor X, I later add multiple methods in the file using X.prototype.method = function () {...}. Although technically an assignment statement, it behaves like a function declaration, which typically doesn't requi ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

Displaying parent component when URL changes in Vue Router for child components

Currently, I am delving into the world of Vue and encountering an issue with nested routers. Despite defining some child routers in the routes, whenever I access the child route, the parent component continues to be displayed. Below is the snippet of my co ...

What could be preventing my PHP function from being executed when the button is clicked?

My PHP block has all the working get functions as expected. <?php function getTitle() { $connection = new PDO('mysql:host=x.x.x.x;dbname=x;charset=utf8', 'x', 'xxxx'); $query = $connection->query("SELE ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

__zone_symbol__currentTask Exception

I encountered an Error message: {"__zone_symbol_currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","cancelFn":null,"runCount":0}} Here is the corresponding code snippet: async getNewData(id: number, path: ...

Issue: Node Sass 8.0.0 is not compatible with the version ^4.0.0

I encountered an error when starting a React app with npm start. How can I resolve this issue? ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneO ...

Calculating the Return on Investment (ROI) for Masternodes: A Comprehensive

Is there a way to calculate the ROI of each masternode without using traditional APIs? I will reveal how this can be done. Utilizing data from CoinMarketCap, you can access valuable information about prices and market capitalization. However, determining ...

Develop a Modal Form using Bootstrap (HTML)

I followed a tutorial on creating a modal form with Bootstrap, you can find it here: http://www.youtube.com/watch?v=HCEbp07hfLw I replicated the steps shown in the video, but when I try to open the page in my browser, nothing appears. I have added the Bo ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...