What is the best way to access the version number of a nested array of objects while excluding one attribute or level in

I am trying to fetch a version of an object without the specific details. In other words, I want to retrieve everything except the Trades element in the nested array of objects below.

What would be the most efficient way to achieve this? The list of attributes on each level is much longer than shown here. Is there a method to duplicate everything except one attribute at a certain level or except one level (in this case, keep Trades but remove its Trade node)?

[{
  "SP": {
    "countOrders": 47,
    "count": 0,
    "Orders": [{
      "81803965": {
        "symbol": "RFX",
        "description": "REDFLOW LTD",
        "Trades": {
          "Trade": [{
            "conId": "81803965",
            "tradeId": "17891517",
            "transactionId": "51996490"

I have managed to accomplish this using the following method:

const pfSummary = JSON.parse(JSON.stringify(portfolios));
var key;
pfSummary.forEach(function (pf) {
  for (x in pf) {
    key = x;
    break;
  }
  pf[key].Orders.forEach(function (or) {
    for (x in or) {
      key = x;
      break;
    }
    delete or[key].Trades;
  });
});

While this solution works, I believe there may be a more effective approach to achieve the same outcome, particularly in how we retrieve an object's key...?

If you have better suggestions or solutions, please share them!

Akabin's revised solution:

pfSummary.forEach(pf => {
  let pfKey = Object.keys(pf);  
  pf[pfKey].Orders.forEach(or => {
    let orKey = Object.keys(or);
    delete or[orKey].Trades;
  });
});

Answer №1

This code snippet demonstrates how to manipulate object data in JavaScript.

let portfolioSummary = [{
  "SP": {
    "totalOrders": 47,
    "count": 0,
    "ordersData":  [{
      "81803965": {
        "symbol": "RFX",
        "description": "REDFLOW LTD",
        "tradesData": {
          "Trade": [{
            "conId": "81803965",
            "tradeId": "17891517",
            "transactionId": "51996490"
          }]
        }
      }
    }]
  }
}]

portfolioSummary.forEach(entry =>{
    let entryKeys = Object.keys(entry);
    for (const key of Object.entries(entry[entryKeys].ordersData[0])) {
        delete key[1].tradesData['Trade'];
    }
})

console.log('portfolioSummary', portfolioSummary)

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

Troubleshooting: Angular.js Functionality Failing to Execute in Plunker

Could you please review This Plunker Demo and provide insights on why it is not functioning correctly? Below is the code snippet I am using: <!DOCTYPE html> <html ng-app> <head> <script data-require="<a href="/cdn-cgi/l/ema ...

I am facing a problem with the API routes in my Next.js project as the req.query object is coming up as undefined

Issue: I'm facing a problem with accessing query parameters in my API route. Despite sending the correct URL with the query parameter, req.query is returning undefined data instead of the expected values. Here's the Request Handling Code: impor ...

Ways to add AJAX information to select2

I am currently utilizing a select2 dropdown feature and I am attempting to configure it in such a way that it dynamically displays the leads based on the JSON response. As you can observe in the image provided below, the text correctly yields a JSON array ...

Error: The object 'window' is not recognized - Issue with Next.js slider

I'm having trouble debugging a reference error issue on Windows. ReferenceError: window is not defined at /home/ubuntu/Desktop/project/my-app/node_modules/@splidejs/splide/dist/js/splide.js:5857:1 at Object.<anonymous> (/home/ubuntu/Desk ...

Guide to iterating through a queue of promises (sequentially handling asynchronous messages)

Currently, I am working on processing a queue of promises (which are representations of messages) in a specific order and using AngularJS for the task. Just to give you an idea, let's say that I have a method called connect() which returns a promise ...

What is the best way to send information from an MVC controller to JavaScript?

Being new to programming, I am working on 2 projects that function as client-server via Rest API. I am looking to create a column chart using data from a List of ID (participant) and Votes (Total votes) obtained from the server's connection with the d ...

Retrieving data from an array with knockout.js

I have a function that receives an array and I want to extract the information from it to display on the page. Here is how the array is structured: EducationalClasses: [object, object] The first object contains: classId: "324342", className: ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

Retrieve values from an array containing objects using JavaScript

As I am exploring Firebug, I encountered an issue where the console log of an array shows: Array [ ] Even though in the right panel of Firebug it is visible that the array contains 3 objects, I am unable to access them. Is there a way to retrieve these va ...

What is the best way to visually refresh a polymer element that displays data from a frequently changing URL?

Hey there! I'm currently facing an issue with displaying a polymer element that contains some important information. This element is supposed to appear when I tap on an icon, but for some reason it doesn't show up even after the data has been loa ...

NextJS does not support the rendering of the map function

Currently, I am getting acquainted with NextJS by creating a basic blog. I have successfully passed the data through props and can see it logged in the console within the map function. However, I am facing an issue where the HTML content does not display i ...

What is preventing me from utilizing a dynamic import while working with Nuxt3?

I'm currently working on developing a component that allows me to dynamically import icons based on the provided icon name using unplugin-icons. However, I'm facing an issue where dynamic imports don't seem to work when the import path is dy ...

The required validator in Mongoose is not being triggered by the function

I'm trying to use a function as a validator in a mongoose schema, but it doesn't seem to work if I leave the field empty. The documentation states: Validators are not run on undefined values. The only exception is the required validator. You ...

Rotation of table columns slider

My goal is to design a table layout with 4 columns, but only display 3 columns at a time. I plan to achieve this by using a div that spans the width of the 3 visible columns and applying overflow: hidden to hide the last column. When the button is clicked, ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Updating nested data in MongoDB without creating duplicate objects

My goal is to add new data into an existing document: Graph.update( { id: id }, { $push: { tooltips: { element: Session.get('tooltipID'), text: text } } } ); E ...

Traversing through intricate weather data in JSON with AngularJS

I've been diving into learning angularJS and have hit a roadblock when it comes to extracting values from specific objects in a JSON file. Despite searching online for solutions, all I've found are basic examples that don't quite fit my curr ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

I encountered difficulty clicking a button due to its unique button data-order-group-id while using python and selenium

Need help with javascript code for repeating orders: <div class="col-ea-1 repeat-order repeatable-order"> #common row in other snippets <button data-order-group-id="a9755447-04ff-4d00-59bf-06ff87f8ead6" #different row data- ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...