Ways to obtain the value associated with a particular key within an object and its descendant elements?

When working with form outputs, I encountered an object structure that includes field names and a key "value" representing the value. Sometimes, the field itself is another object with its own "value" key. My goal is to extract only the values stored within the "value" keys. Here's an illustration:

Original Object:

{
  inputA: 1354,
  inputB: "String Value",
  inputC: [
    {
      value: 1,
      label: "Value 1"
    },
    {
      value: 2,
      label: "Value 2"
    },
    {
      value: 4,
      label: "Value 3"
    }
  ],
  inputD: {
    value: 16,
    label: "Value 16"
  },
  inputE: {
    value: 1,
    label: "Value 1"
  },
  inputF: {
    subInputA: {
      value: "String Value",
      label: "Value of Value"
    },
    subInputB: {
      value: 1,
      label: "Value 1"
    }
  }
}

Desired Result:

{
  inputA: 1354,
  inputB: "String Value",
  inputC: [1, 2, 4],
  inputD: 16,
  inputE: 1,
  inputF: {
    subInputFA: "String Value",
    subInputFB: 1
  }
}

Answer №1

I have the solution to your request. It will provide the expected output as you specified.

//Here is the original object
let originalObject = {
  inputA: 1354,
  inputB: "String Value",
  inputC: [
    { value: 1,  label: "Value 1"  },
    { value: 2,  label: "Value 2"  },
    { value: 4,  label: "Value 3"  }
  ],
  inputD: { value: 16,  label: "Value 16" },
  inputE: { value: 1,   label: "Value 1"  },
  inputF: {
    subInputA: { value: "String Value", label: "Value of Value"  },
    subInputB: { value: 1,    label: "Value 1"  }
  }
}

//Expected output
/*
{
  inputA: 1354,
  inputB: "String Value",
  inputC: [1,2,3],
  inputD: 16,
  inputE: 1,
  inputF: {
    subInputFA: "String Value",
    subInputFB: 1
  }
}
*/

//My code
let ans = {}

function digDeep (obj){
    if(typeof obj ==='number' || typeof obj === 'string') return obj
    else if( typeof obj === 'object' && obj.length===undefined){
        let keys = Object.keys(obj)
        if(keys.indexOf('value')!=-1) return obj.value
        let pom = {}
        keys.forEach(key=> pom[key]=digDeep(obj[key]) )
        return pom
    }else if( typeof obj ==='object' && obj.length>0) return obj.map(el=>digDeep(el) )
}

ans = digDeep(originalObject)

//Print the output
console.log(ans)
 

Output:

{ inputA: 1354,
  inputB: 'String Value',
  inputC: [ 1, 2, 4 ],
  inputD: 16,
  inputE: 1,
  inputF: { subInputA: 'String Value', subInputB: 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

Why is the React Redux child component unable to access props?

Struggling with React and Redux? Here's the issue: A Component in my project is supposed to receive a value from Redux using mapStateToProps. The problem arises when trying to access this value within the child Component's renderFoo() function. ...

Tips on stopping form submission and opting for a jQuery ajax call instead

I am encountering an issue where I have an event set up to trigger when the return key is pressed on a form input field. However, instead of the ajax call being fired as expected, the form is submitted like a regular http request. $("#addurl").keypress(fu ...

Incorporating user names into socket.io chat for disconnect functionality

I've recently started using socket.io and have been developing a messaging chat feature. By adding usernames to the chat upon login and message submission, everything seemed to be working smoothly. However, I'm facing an issue with retrieving use ...

The scroll animation shows unpredictable behavior when moving in both directions, and there may be a delay in response when using the

I'm attempting to create a smooth scroll effect to move to an element at the bottom of the page when scrolling down, and another element at the top of the page when scrolling up. Both elements have a height of 100vh. However, once I start scrolling d ...

Issue with BCRYPTJS library: generating identical hashes for distinct passwords

After conducting a thorough search on Google, I couldn't find anyone else experiencing the same issue. The problem lies in the fact that no matter what password the user enters, the system returns the hashed value as if it is the correct password. Eve ...

Creating a tree control using JSON and jQuery: A step-by-step guide

I am currently working on creating a dynamic tree view on my website using jQuery and JSON data. Each node in the tree comes with an associated checkbox, and I want to implement a functionality where clicking on a parent node automatically selects all its ...

Encountered an issue while trying to access the 'value' property from an undefined field in the available options

When attempting to showcase the value of the select field, I encountered this error message: Cannot read properties of undefined (reading 'value') https://i.stack.imgur.com/Q0d2k.png You can find the codesandbox link here: https://codesandbox.i ...

Is it feasible to have a set number of character lines per <p> tag without relying on monospaced fonts?

I am facing the challenge of breaking a large text into paragraphs of equal size, with the same number of string lines in order to maintain uniformity. Currently, I am using PHP and the following code to achieve this: function arrangeText(){ if (have_ ...

Can Firebase data be updated in real-time in a Vue app?

Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user. The objective is to seamlessly display the list of friends while refle ...

Easy Guide to Consuming Rest APIs with Spring and AngularJS That Does Not Retrieve or Display Data

I'm currently working through this specific guide step by step, but unfortunately I'm encountering some issues with loading the JSON content successfully. These are the files I've generated following the guide: index.html: <!doctype ht ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Discover the specific span being modified within a div

Recently, I coded some HTML: <div id="contentbox" contenteditable="true"><span value="1">Hello</span><span value="2">Stack</span><span value="3">over</span> flow</div> Additionally, I used jQuery to enhance ...

Restricting the user to input only once, using MeteorJs framework

I have been developing an application that allows users to book courses, and I am looking to restrict them to booking each course only once. Below is the current code snippet that I have written for this functionality, and any assistance from you all would ...

Determining the bit size of individual elements within a struct array

Presently, my struct has this layout: struct Struct { uint8_t val1 : 2; uint8_t val2 : 2; uint8_t val3 : 2; uint8_t val4 : 2; } __attribute__((packed)); Is there a method to consolidate all the val variables into a single array? The focus ...

The building process of Ember encountered an error due to a problem with the broccoli builder

I'm currently working on an Ember project and facing an issue while trying to upgrade the version from 2.8 to 3.5.0. After changing the version and some dependencies, I encountered the following error : Error stack Even after attempting to resolve i ...

What is the most effective method for transferring an error message from the server backend to the vue frontend?

I'm currently working on implementing error handling for a Vue/Vuetify application. The challenge I'm facing involves using external pagination for a datatable that connects to an API with rate limiting restrictions. If users exceed the limit, I ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

Array initialization error: java.lang.NullPointerException

I've encountered a strange error while trying to initialize an array. After creating the array, I'm getting a java.lang.NullPointerException. Here is how I'm doing it correctly (For this example, data.length / 4 equals 1): short[] data = By ...

Search for spaces and brackets in a file name, excluding the file extension using Regular Expressions

Currently utilizing javascript and I have a specific string let filename1 = "excluder version(1).pdf" Keep in mind that the extension may vary, like jpg or png I am looking to replace the original string with the desired outcome is it possible ...