Finding the most recent instance of a deeply buried value based on a specific property

I have an example object:

const obj = {
    group: {
        data: {
            data: [
                {
                    id: null,
                    value: 'someValue',
                    data: 'someData'
                }
            ]
        }
    }
};

My objective is to retrieve a value by property name.

In this case, I am trying to get the value of the data property, specifically the last occurrence of it.

Therefore, the expected output should be:

someData

However, I am using a recursive function to achieve this:

const findVal = (obj, propertyToExtract) => {
  if (obj && obj[propertyToExtract]) return obj[propertyToExtract];

  for (let key in obj) {
      if (typeof obj[key] === 'object') {
          const value = findVal(obj[key], propertyToExtract);
          if (value) return value;
      }
  }
  return false;
};

The current function returns the value of the first occurrence of data, like so:

data: [
    {
       value: 'someValue',
       data: 'someData'
    }
]

What can be done to obtain the desired result?

Answer №1

One potential approach involves recursively flattening the object and targeting the desired index (in this case, 'data').

const object = {
group: {
    data: {
        data: [
            {
                id: null,
                value: 'someValue',
                data: 'someData'
            }
        ]
    }
}
};

function deepFlatten(object) {
  let flattenedObject = {};
  flatten(object,flattenedObject);
  console.log(flattenedObject);
  return flattenedObject;
}

function flatten(toFlatten, flattenedObject) {
  Object.entries(toFlatten).forEach(element => {
    if (element[1] && typeof element[1] === 'object') {
     flatten(element[1], flattenedObject);
    } else {
      flattenedObject[element[0]] = element[1];
    }
  });
}

let output = deepFlatten(object);
console.log(output['data']);

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

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

Toggle button color on click by using ng-click on a different button

As a newcomer to Angular, I am facing an issue. I have two buttons - button1 and button2. What I want is that when I click on button1, its color changes from green to red. Then, when I click on button2, the color of button1 should revert back to green. How ...

Navigate to a list item once Angular has finished rendering the element

I need to make sure the chat box automatically scrolls to the last message displayed. Here is how I am currently attempting this: akiRepair.controller("chatCtrl", ['$scope', function($scope){ ... var size = $scope.messages.length; var t ...

Looking to enclose a search query in JavaScript using quotes, and then remove the quotes on the Python backend

Let's start with my code snippet. This is the HTML section: <form action= "/" onSubmit= "return validate(this);" method= "post"> <!--irrelevant from this point--> Below is the Javascript portion, located later in the file: <scri ...

How to avoid an additional carriage return in Internet Explorer when editing a Textarea?

In Internet Explorer, we are facing an issue with a multiline textarea. After setting the content using JavaScript and checking it, everything appears correct without any additional carriage returns in the textarea: document.getElementById( 'text-ar ...

reloading a webpage while keeping the current tab's URL selected

I want to incorporate a feature I saw on the jQuery website at http://jqueryui.com/support/. When a specific tab is pressed, its contents should open. However, when the page is refreshed, the same tab should remain open. I'm trying to implement this i ...

How can transitions be activated in Bootstrap 4 carousel?

Having an issue with my Bootstrap 4 carousel where I need to move 4 slides at a time. I have tried using the code below: $(this).carousel(4); However, the problem is that the carousel only jumps to that index without showing any transitions. Using $(this) ...

several javascript onclick event listeners for manipulating the DOM

I am currently experimenting with d3 and attempting to create a simple webpage to showcase my d3 examples for future reference. The page displays the output of the d3 code (specifically, the force layout from Mike Bostock) and then embeds the correspondin ...

Having trouble executing react-native project using the command "npx react-native run-android"

Hey there! I've been working on a react-native project for quite some time now and everything was going smoothly until yesterday. I encountered an error when running the command npx react-native run-android in Metro before the project had fully execut ...

Unable to update innerHTML of asp.net literal tag using JavaScript

Here is a snippet of my JavaScript code: <script type="text/javascript">function CountCharacters(idTxtBox, idCharCount) { var maxLimit = 500; var remainingChars = maxLimit - document.getElementById(idTxtBox).value.length; do ...

Issue with jQuery DataTable: Unable to use column-level filters at the top and maintain a fixed height simultaneously

I am having an issue displaying data in a jQuery DataTable with a column level filter at the top, fixed height, and scroller enabled. Initially, I was able to display the column level filter at the top and it was functioning properly. However, when I set t ...

Transforming a JSON string containing multiple arrays into a JavaScript object

My JSON file is structured as follows: { "items":[ { "username":"abc", "orderID":"1234", "commentHistory":[ { "comment":"Comment Date: 2016/12/09 13:44:23" }, { ...

What could be the reason behind the Vue property being globally undefined in the component at the time of mounting?

Creating a custom Vue plugin was essential for me, which establishes a global property on Vue in this way: function (Vue, options) { Vue.$detector = new TranslatableStringDetector(); } Utilizing it within a computed property in my component is done l ...

Conditions in Controller Made Easy with AngularJS

I have recently started working on implementing a notifications feature. The service will involve making a GET request to a specific URL which will then return an array of notifications. Within the controller, I am in the process of setting up a variable ...

All Event Monitor

Is it possible to use Event Listeners in jQuery to display information when a specific word is clicked? For example, showing a definition when a word is clicked. Thanks, Adam. I need help with creating a feature where clicking on a person's name in a ...

There was a rendering error: "Type Error: Unable to access the 'PAY_TYPE' property of null"

I am attempting to retrieve the PAY_TYPE value from the callback_details object by using JSON.parse() function to convert a string into an object. However, I keep encountering an error related to the question's title. Here is my code snippet: <td ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

What is the best way to trigger a localstorage change event using Vue.js?

I'm currently facing an issue with my Vue app related to updating user information stored in localStorage. I've implemented a solution using websockets in App.vue within the mounted function, as shown below: window.Echo.channel("user." ...

How to Conceal the <th> Tag with JavaScript

I attempted to conceal certain table elements using JavaScript. For <td> elements, it works fine: function hide(){ var x=document.getElementsByTagName('td'); for(var i in x){ x[i].style.visibility='hidden'; ...

JavaScript - Uncaught ReferenceError: WebSocket is undefined

Looking at just the client side API (since each server side language has its own API), this code snippet demonstrates opening a connection, setting up event listeners for connect, disconnect, and message events, sending a message to the server, and closing ...