Retrieve a dynamic value from an object

Is it possible to dynamically pass a context from the server to the client so that the client can retrieve a value from an object more efficiently?

For example, the server sends an object with a key-value pair like this:

"booking__validating_carrier__iata": "Cia"
.

The key

booking__validating_carrier__iata
can be translated into an array
['booking', 'validating_carrier', 'iata']
. The goal is to access the value
order['booking']['validating_carrier']['iata']
or
order.booking.validating_carrier.iata

I'm trying to figure out a way to access the object without hardcoding the indexing levels. One approach I came up with is:

if(arr.length === 1) {
  order[arr[0]]
} else if(arr.length === 2) {
  order[arr[0]][arr[1]]
} else if(arr.length === 3) {
  order[arr[0]][arr[1]][arr[2]]
} else if(arr.length === 4) {
  order[arr[0]][arr[1]][arr[2]]
} else if(arr.length === 5) {
  order[arr[0]][arr[1]][arr[2]][arr[3]]
}

Is there a more efficient way to loop through the array length to access nested properties of the object?

Thank you!

Answer №1

To simplify the array, you can utilize the reduce method and set order as the starting point. The nested object will then act as the accumulator during each iteration.

arr.reduce((acc, k) => acc[k] || {}, order)

Check out this code snippet:

const nested = {
  "1": {
    "1.1": {
      "1.1.1": "3 level nesting"
    },
    "1.2": "2 level nesting"
  }
}

const getValue = (order, arr) => arr.reduce((acc, k) => acc[k] || {}, order)

console.log( getValue(nested, ["1", "1.1", "1.1.1"]) )
console.log( getValue(nested, ["1", "1.2"]) )

Answer №2

To accomplish this task, one approach is to use a recursive function. This function will continue iterating until either the array runs out of data fields or the object no longer contains nested objects that match the array fields.

const arr = ['category', 'subcategory', 'item'];

const data = {
  category: {
    subcategory: "example"
  }
}

const recursiveFunction = (element, array, index) => {
  if(array[index] !== undefined && element[array[index]] !== undefined) {
    return recursiveFunction(element[array[index]], array, ++index);
  } else {
    return element;
  }
}

console.log(recursiveFunction(data, arr, 0));

Alternatively, you could opt for a for loop:

const arr = ['category', 'subcategory', 'item'];

const data = {
  category: {
    subcategory: "example"
  }
}

let finalResult = data;
for(field of arr) {
  if(finalResult[field] !== undefined) {
    finalResult = finalResult[field];
  }
}

console.log(finalResult);

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

Transform MONGODB BSON data into JSON using Bash

I have a command that calls MongoDB and generates BSON output. To parse this output using jq, I need to convert the BSON to JSON with jq's tojson function. echo "db._adminCommand({replSetGetStatus : 1})" | /path/to/mongo How can I use tojson? Would ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Angular and Spring are producing a 415 Unsupported Media Type error

I have encountered a dilemma where I tried multiple solutions to no avail. The angular service code is as follows: app.factory('service',['$http','$q', function($http,$q){ return { get: function(m){ return $http.p ...

Is it beneficial to vary the time between function calls when utilizing setInterval in JavaScript?

My website is displaying two words one letter at a time, with a 0.1s delay between letters and a 3s pause after each full word. I attempted using setTimeout, but it's not functioning as expected. What could be the issue in my code? var app = angular. ...

create a function that returns JSX in React

Having trouble with the FilterBydescription component in the Render function. I am expecting to return JSX elements, but instead I am getting undefined in UseAdvertisementsFilters. It seems like the context is getting lost somewhere, but I can't figur ...

Get the JS file by tapping the download button, and access the

In creating the web page, I utilize a modular approach. Leveraging node js and the node-static server are essential components of this process. One specific requirement I have is implementing file downloads from a computer to a device using a button trigg ...

Styling Challenges with CSS/AngularJS Accordion in Footer

I want to create a page layout as shown below: +---------------------------+ | Auto-fill / v scrollable ^| | || | || | v| +---------------------------+ | Fixed [][][] ...

Transferring data from a class method to a React component

Situation: In a React component, I have a class with its own methods that is instantiated. What I'm needing: One of the methods in the class changes the value of an input (referred to as `this.$el`) using `.val()`. However, I need to pass this value ...

Utilizing SetInterval for dynamically changing the CSS background image URL

I'm starting to feel frustrated with this situation... I have a solution where the CSS background is coming from a webservice. Currently, the system refreshes the entire page using HTML: <meta http-equiv="refresh" content="300" /> ... body { ...

Setting the default date format in dayjs: A quick guide

Is there a way for me to set the default date and time format to "YYYY-MM-DD HH:mm:ss" in order to avoid unnecessary repetitive code like the following: this.dayjs().startOf("year").format("YYYY-MM-DD HH:mm:ss") this.dayjs().format("YYYY-MM-DD HH:mm:ss") t ...

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

Exploring ways to check async calls within a React functional component

I have a functional component that utilizes the SpecialistsListService to call an API via Axios. I am struggling to test the async function getSpecialistsList and useEffect functions within this component. When using a class component, I would simply cal ...

Managing images in JavaScript while conserving memory

Welcome I am embarking on a project to construct a webpage using HTML, CSS, JavaScript (jQuery), and nearly 1000 images. The length of the HTML page is substantial, around 5000px. My vision involves creating a captivating visual experience for users as t ...

Tips on conducting a statistical analysis without having to wait for the completion of an AJAX response

I am looking to track the number of clicks on a specific div with the id #counter and then redirect the user to a different website. To achieve this, I have implemented an ajax call on the click event of the #counter div. Upon successful completion of the ...

Activate the Bootstrap Jquery/Ajax inline editing feature by simply clicking on the Edit button

Seeking recommendations for a way to implement inline editing. When the edit button is clicked, I want the label's content to be replaced with an input text field that can be updated in my MySQL database. This is what my code looks like: <label s ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Error in setting cookies using Javascript document.cookie on iOS with cordova-plugin-ionic-webview

Backend-sent cookies are successfully stored, but the app itself cannot set cookies. When running the code snippet below: document.cookie = "notified=1; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"; console.log(document.cookie); An empty strin ...

Install package specifically for a single project

If I have the following file hierarchy: packages/project1 packages/project2 and the workspace is packages/* What is the best way to install an npm package for only project1 and not project2, while ensuring the yarn lock file includes the dependency? ...

What is the process for passing an Object from JavaScript to an Action class in Struts 2?

Within my Action class, there exists an object of the class that is a POJO. public class ConfigureTspThresholdAction extends ActionSupport implements SessionAware, ModelDriven<GmaThresholdParameter>{ private Map<String,Object> session ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...