Efficiently Extract and Append Unknown Nested JSON Values into an Array using JavaScript

It's puzzling why I'm finding this challenging. It seems like there should be a solution using Lodash or a similar tool.

My object is structured like this:

  { "fdjkafdajkfasfjkdaslj": {
      "-LMUD-2APhiSLkEtVbM": {
        "profileName": "bob",
            "profilePic": "www.profilepic.com",
            "score": 73,
            "teamName": "lzs"
        }
    }
  }

I won't know the first two keys in the structure, like "fdjkafdajkfasfjkdaslj" or "-LMUD-2APhiSLkEtVbM".

All I need to do is extract these key values and store them in an array.

       "profileName": "bob",
        "profilePic": "www.profilepic.com",
        "score": 73,
        "teamName": "lzs"

What would be the best approach to achieve this in JavaScript (specifically React.js)? I thought about using Lodash but haven't found a suitable solution yet. Most of my searches for extracting nested Key/Value data from JSON suggest using a path, but in this case, I don't have that information. The only certainty I have is the consistent object structure with two unknown keys preceding the actual key/value data.

Answer №1

If the object in question contains only one key, you can utilize Object.keys()

const data = [];

const obj = { "fdjkafdajkfasfjkdaslj" {
      "-LMUD-2APhiSLkEtVbM": {
        "profileName": "bob",
            "profilePic": "www.profilepic.com",
            "score": 73,
            "teamName": "lzs"
        }
    }
  };
  
  const outerObj = obj[Object.keys(obj)[0]];
  
  const item = outerObj[Object.keys(outerObj)[0]];
  
  data.push(item);

Answer №2

To solve this problem, consider utilizing the Object.values method.

const extractedValue = Object.values( Object.values( strangeObject )[0] )[0]

finalArray.push(extractedValue)

Answer №3

While parsing a JSON string, you can easily locate specific information:

var json = '{"fdjkafdajkfasfjkdaslj":{"-LMUD-2APhiSLkEtVbM":{"profileName":"bob","profilePic":"www.profilepic.com","score":73,"teamName":"lzs"}}}';
var obj;
JSON.parse(json, (key, value) => {
  if (value.profileName) {
    obj = value;
}
});

console.log(obj);

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

Adding an eventListener to the display style of a div in React: A step-by-step guide

I'm currently working on implementing a functionality in React where a Highcharts chart automatically resizes to fit its parent element whenever the parent div is shown. Unlike other libraries, Highcharts doesn't support automatic resizing when t ...

having difficulty applying a border to the popup modal

Currently, I am utilizing a Popup modal component provided by the reactjs-popup library. export default () => ( <Popup trigger={<button className="button"> Guide </button>} modal nested > {(close: any) =&g ...

Return an array with only emails included

Looking to sort through an array specifically for emails, I attempted the following action emails = emails.filter((x)=>(x !== (undefined || null || ''))) To remove any empty values, while still allowing non-email values. ...

Failure in querying with Mongo's $lookup results in an empty array

My $lookup operation on schemas is always returning an empty array. What could be causing this issue? Result Collection const resultSchema = new mongoose.Schema({ trial: { type: mongoose.Schema.Types.ObjectId, ref: 'Trial', requir ...

Arrange objects based on the most recent addition using Vue JS

I am working with a Vue array that consists of 3 objects with names and rates. I have already implemented a function to sort the items by rate: methods: { sortByRate() { this.complejos = this.complejos.sort(function(a, b) { return a.rate - ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

Can someone please guide me on how to transfer information from a material ui datagrid Row to a form input?

I need assistance. I have a table that holds user data and I want to create a functionality where clicking on the edit button opens a dialogue box with a form pre-filled with the user's initial data. However, I'm currently only able to pass the u ...

How come running `npm install <folder>` results in installing different dependencies compared to `npm install lib`?

My current project, project1, relies on <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5221262b3e37367f313d3f223d3c373c262112667c6">[email protected]</a>. When attempting to integrate project2 into project1 as a ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

Is it advisable to consider yarn.lock as a binary file when using git?

Could there be a rationale for this decision? I'm thinking that the potential git diff could occur in package.json. My approach is to consider the yarn.lock file as binary. ...

Find matches between elements based on their names or alt tags and retrieve the associated data

UPDATED FOR BETTER UNDERSTANDING--- I am managing a blog where I want to link images automatically to products in my store. These links will be based on an array generated by Shopify. While I don't have extensive knowledge of jQuery and JSON, I beli ...

My Redux reducer is being overridden by changes made using setState or .map() within my React component

After logging this.state.orginalSeries, this.props.demandGraphSeriesDataReducer, and newSeries, it appears that all data is being mutated. Despite attempting to use .map() and .slice() to prevent mutation of the original reducer data, it seems to still be ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

The URL overwrites the Ajax transfer type

When making an ajax call using a generated URL from a paginator script, I encountered an issue. The URL was dynamically created as shown below: "http://192.168.1.23:8000/pricing/0/999/null/?page=9" A similar link is generated on the server: "https://xxx ...

What steps should I take to resolve the issue with this error message: Error: listen EADDRINUSE

How can I resolve the following issue? system: gulp npm windows issue: ... Oh no. Encountered error listen EADDRINUSE 127.0.0.1:35729 ... Error: listen EADDRINUSE 127.0.0.1:35729 at Object._errnoException (util.js:1021:11) at _exce ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

Step by step guide on rotating a plane with texture by 90 degrees

I've been working on developing an fps game, but I'm encountering an issue where the floor disappears from the scene when I try to rotate it close to 90 degrees. Here's the code snippet responsible for creating the plane. var colorMap = new ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...