How to Call a Nested Object in JavaScript Dynamically?

var myObj = {
    bar_foo : "test",
    bar : {
       foo : "hi there";
         },
    foo : {
          bar : {
                 foo: "and here we go!"
                 }
           }
     }

How can we achieve the following:

var arr = [["bar", "foo"], ["foo", "bar", "foo"]];

to produce these results:

myObj["bar"]["foo"];
myObj["foo"]["bar"]["foo"];

The array arr may vary in length, allowing it to explore the object fully.

We are aware that we can access an object's value dynamically as shown below:

var normally = myObj["bar_foo"];

where normally would be equal to "test"

However, this method assumes a predetermined depth for traversing the object.

I am attempting to retrieve an object's value by providing an array such as:

["bar", "foo"]

This is essentially equivalent to:

myObj["bar"]["foo"];

The objective behind this approach is to create a new object based on specific values extracted from arr.

Consequently, the final outcome would be:

arr_new = myObj.someMethod(arr);

where arr_new represents:

arr_new : ["hi there", "and here we go!"];

Hopefully, this explanation provides clarity on the matter.

Answer №1

If you are working with Underscore (or have access to native JS map and reduce), consider implementing the following approach:

var myObject = {
  bar: {
    foo: "hello there"
  },
  foo: {
    bar: {
      foo: "let's get started!"
    }
  }
};

var array = [
  ["bar", "foo"],
  ["foo", "bar", "foo"]
];

function retrieveDeepProperty(arr, obj) {
  return _.reduce(arr, function(prevVal, currentVal) {
    return prevVal[currentVal];
  }, obj);
}

var deepProperties = _.map(array, function(nestedArray) {
  return retrieveDeepProperty(nestedArray, myObject);
});

console.log(deepProperties); // => ["hello there", "let's get started!"]

While there could be a more refined solution available, this serves as a quick workaround that achieves the desired outcome! :P

Answer №2

CustomFunction.prototype.newMethod = function (arr) {

  function customFunction (obj, array){
    var res = obj[array.splice(0, 1)[0]];
    if (typeof res === 'object' && array.length) {
      return customFunction(res, array);
    }else{
      return res;
    }
  }
  var resultArray = [];
  for (var index = 0; index < arr.length; index++) {
    resultArray.push(customFunction(this, arr[index]));
  }
  return resultArray;
};

JSBin >> Demo

Answer №3

Could this be the solution you’ve been searching for?

function extractObjValue( arr, obj){
    var temp=obj;
    for(i=0;i<arr.length;i++){
        temp=temp[arr[i]];
    }
    return temp
}

alert( extractObjValue( arr[1],myObject)); // "and voilà!"

If creating an array of values is what you need:

var outcome=arr.map(function(subArray){
   return  extractObjValue(subArray,myObject);
})

Check out the DEMO

Answer №4

Here is a fiddle I created showcasing a potential solution, all without the use of libraries:

http://jsfiddle.net/EfrainReyes/6s9HY/2/

function extractData(object, array) {
    var results = [];

    for (var i = 0; i < array.length; i++) {
        var tempObj = object;

        for (var j = 0; j < array[i].length; j++) {
            tempObj = tempObj[array[i][j]];
        }

        results.push(tempObj);
    }
    return results;
};

It's important to note that this function assumes valid parameters are passed in, however, you can always add validation checks as needed.

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

"X-Requested-With" header not being included in XMLHttpRequest request

After successfully using jQuery.ajax() to make an ajax call to an MVC action, I decided to switch to using the XMLHttpRequest along with the HTML5 File API due to some forms containing file controls. However, since making this change, the MVC action no lon ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...

Is there a way to invoke a jQuery function from an ASP.NET environment?

I'm having trouble figuring out how to properly invoke a jQuery function. ScriptManager.RegisterStartupScript(GetType(), "Javascript", "countdown(); ", true); The issue is that it attempts to call the method inline, preventing it from executing the ...

Launching my initial React application

After creating a small React app using the boilerplate available at https://github.com/vasanthk/react-es6-webpack-boilerplate I was able to run it smoothly on my localhost. However, I am now facing confusion on how to configure it for live deployment. F ...

Exploring the intricacies of debugging async/await in Node.js with the help of

Having trouble debugging an "await" instruction in my async function. Every time I try, a promise is returned instead of the expected value. I've noticed there's supposed to be an "Async" button where the red square is located in this picture but ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Discover the secret to incorporating concealed text in WordPress with a hidden div through the power of JavaScript

For a while now, I've been trying to implement a functionality where clicking on a text reveals a dropdown menu with more information, similar to a "read more" feature. I have limited experience in Java or jQuery, and I can't figure out if the i ...

What is the best way to transfer data between different states in ReactJS components?

I am in the process of developing an application that will showcase a list of categories. Upon selecting a category, the application will transition to the next page where a query regarding water type will be posed. Once the water type is chosen, the app s ...

Attempting to store an array of JSON objects in the state, and then utilizing the `map` method to render

I'm just starting out with React. Currently, I'm attempting to store an array of JSON objects in the state and then map those items into the component render. I'm feeling a bit lost on how to debug this as there are no console errors showi ...

Exploring the process of iterating through arrays within an object in vue.js using the v-for directive

Is there a way to iterate through an output object using the v-for template in Vue.js? new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [14, 165, 113, 19, 22], }, }, }); <script src= ...

The content is not displayed in the d3 visualization

While examining the code of this visualization found at http://bl.ocks.org/mbostock/4062045, I noticed that the name from the JSON file is not displaying alongside the nodes. Even though the code includes: node.append("title").text(function(d) { return ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

Managing media file transfers using multer and mongodb in a Node.js environment

As I work on developing a blog-style application for a business website, I have successfully implemented a login system and a basic blog structure. My current focus is on enabling users to upload images along with their blog posts. At the moment, I am trou ...

Can a web application be developed utilizing JavaScript to access the torch feature in Safari?

Currently working on a website that needs to utilize the flashlight feature on both android and IOS devices. Found a method to activate the torch from an android device using Chrome (link). However, this same code does not seem to be functional on my IOS d ...

Initiate a POST ajax request to retrieve the file.Let's

I'm currently working on an Asp.Net MVC project and I have a piece of code in my View that looks like this: $.ajax({ beforeSend: function () { LoadStart(); }, complete: function () { LoadStop(); ...

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

A sleek and streamlined scrollspy that dynamically updates the active class exclusively for anchor tags

Can anyone help me with this coding problem? I'm currently working on a minimalistic scrollspy code that adds an active class when the content is offset.top. The code works fine, but I want to change the active class to apply to the "a" tag instead of ...