What is the method to retrieve JSON data with data['file.file']?

When trying to query my data using var x = data.file.file;, I encountered an issue where data['file.file'] fails. Is there a way to access this data without having to split the string and walk recursively through it?

Answer №1

Avoiding the use of eval is crucial in JavaScript to ensure secure and efficient code execution. One way to accomplish this is by employing string splitting techniques instead. This approach can be seen in the following example:

var info = {
  data: {
    value: 'HELLO'
  }
};

fetchValue(info, 'data.value'); // "HELLO"
setValue(info, 'data.newprop.blob', 7); // false
setValue(info, 'data.newprop', {}); // true
setValue(info, 'data.newprop.blob', 7); // true
console.log(info); // {data: {value: "HELLO", newprop: {blob: 7}}}

function fetchValue(object, path){
  var parts = path.split('.'), undefined, index;
  for(index = 0; index < parts.length; index++){
    object = object[parts[index]];
    if(object === undefined) return undefined;
  }
  return object;
}

function setValue(object, path, newValue){
  var parts = path.split('.'), undefined, index;
  for(index = 0; index < parts.length - 1; index++){
    object = object[parts[index]];
    if(object === undefined) return false;
  }
  object[parts[index]] = newValue;
  return true;
}

Answer №2

data['file.file'] is referencing a property within the data object called 'file.file', whereas data.file.file is pointing to the file property within the file property of data.

To achieve the same access as data.file.file, use data['file']['file'] instead.

Update:

In order to utilize the multi-array access method, you will need to split your string accordingly. For example:

var path = 'file.file'
var pathElems = path.split('.')

// accessing the field
data[pathElems[0]][pathElems[1]]

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

byte sequence displays as binary data (angular + express)

I've been working on pulling files from a back-end Node.js / Express server and displaying them in an Angular front-end. Despite trying different methods, I keep facing the same issue - the data displayed at the front-end appears as a bytestring. Even ...

Implementing image change on dropdown selection using jQuery click event

I'm new to Jquery and JavaScript. I have a dropdown in my Keen template that displays 2 flags. I want to be able to click on the dropdown and select the corresponding flag. Most of the examples I found online use the select and options tags, but my co ...

Implementing JSON data binding for webgrid in ASP.net MVC4

I am struggling to populate a webgrid with Datatable values using Json. I have implemented a DropDownlist to select a person's name, and based on that selection, I want to display the corresponding data in the webgrid. However, my current code does no ...

Create waypoints on multiple elements

I am working on implementing a unique feature using a div tag with the class "dipper." <div class = "dipper"> <p>Peekaboo</p> </div> As part of this implementation, I have included a script that triggers the display of the "dipper ...

Tips for identifying the cause of a memory leak in browser notifications

I am looking to implement browser notifications in a browser extension. However, I have noticed that the memory usage does not decrease after closing the notification. Can someone explain why this may be happening? Allow StackOverflow show notifications i ...

jquery unclean data, in need of the jquery ui popup dialog

I have been experimenting with this library to determine if a form is dirty. By default, it triggers the standard browser confirmation asking whether you are certain about navigating away from the page. The jquery dirtyforms website includes a section sugg ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Error message "env: '/bin/flask': No such file or directory" pops up while executing the command "npm run start-backend"

Currently on the hunt for a super basic website template that combines Flask and React. I've been using this repository and carefully following the installation steps laid out https://github.com/Faruqt/React-Flask Working on Windows 10 using git Bas ...

When using Rspec and Capybara, utilizing jQuery to set focus on an element may not apply the `:focus` CSS as expected

I have implemented jump links for blind and keyboard users on my website, but I've hidden them off-screen visually. When these links gain focus, they are moved into the viewport. Trying to test this behavior using RSpec and Capybara has been unsucces ...

Using React hooks to reset state in a reducer: step-by-step guide

event.js import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { addEvent } from '../actions/event'; ...

Extrude a face in Three.js along its respective normal vector

My goal is to extrude faces from a THREE.Geometry object, and my step-by-step approach involves: - Specifying the faces to be extruded - Extracting vertices on the outer edges - Creating a THREE.Shape with these vertices - Extruding the shape using THREE.E ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

Encountering a registration error persistently: [TypeError: Network request failed]

Currently, I am in the process of developing an application using React for the frontend and node.js for the backend. However, I have encountered a persistent network error whenever I try to sign up or log in. What puzzles me is that when I test the API en ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

The table value is only updated once with the onclick event, but the updated value is not displayed when the event is clicked again

I am facing an issue with updating names in a table through a modal edit form. The first name update works perfectly, but the second update does not reflect in the table. I want every change made in the modal edit form to be instantly displayed in the tabl ...

Choosing a radio button based on the stored value within a variable

When transferring a variable (active) from my route to EJS, I initially found it easy to simply display its value: <!-- Active Text Input--> <div class="form-outline mb-4"> <label for="active" class="form-label">Active</label> ...

What are the key distinctions between Cordova and PhoneGap?

After reviewing multiple documents, it appears that Cordova is often described as a power booster for PhoneGap. However, I am interested in understanding the differences between the two during implementation. When creating a project using Cordova via the ...

Rotate Text in HTML <thead> Tag

I need assistance with rotating a table header. https://i.stack.imgur.com/hcvxx.png The HTML th elements within the thead section are described as follows: <th> <span class="rotate-all">Period</span> </th> <th> < ...

Retrieving cascading values in a dropdownlist using Asp .NET MVC

In my current project, I am using Asp.Net MVC4. In a form, I have implemented cascading dropdown lists. When I select "Distrito" in one dropdown list, it correctly loads the corresponding values for "Sucursal". The insertion of records works fine. However, ...

Is there a way to logout when the select event occurs using the key?

I am trying to figure out how to log out the key value when the select event is triggered. Specifically, I want to access the key={localState.id} within the <select></select> element in my HTML. This key value is crucial for a conditional stat ...