Generate a fresh array using the data from the existing array object

I have nested objects within arrays that I need to manipulate.

{
  "page": [
    {
      "num": "1",
      "comp": [
        {
        "foo": "bar",
        "bar": "foo",
        "name": "comp1",
          "items": [
            {
              "fooBar":"barFoo",
              "itemData": 
                {
                  "foo": "bar",
                  "bar": "foo",
                  "fooBar": "barFor"
                }
              
            }
          ]
        }
      ]
    },
    {
      "num": "2",
      "comp": [
        {
        "foo": "bar",
        "bar": "foo",
        "name": "comp2",
          "items": [
            {
              "fooBar":"barFoo",
              "itemData": 
                {
                  "foo": "bar",
                  "bar": "foo",
                  "fooBar": "barFor"
                }
              
            }
          ]
        },
        {
          "items": [
            {
              "fooBar":"barFoo2",
              "itemData": 
                {
                  "foo": "bar",
                  "bar": "foo",
                  "fooBar": "barFor"
                }
              
            },
            {
              "itemData": 
                {
                  "foo": "bar",
                  "bar": "foo",
                  "fooBar": "barFor"
                }
              
            }
          ]
        }
      ]
    },
    {
      "num”: "3”
    }
  ]
}

My goal is to create a new array containing only the itemData, while maintaining the structure of the original object.

To achieve this, I plan on using nested for loops to access the itemData object:

for (const [i, page] of this.testingAnimation.pages.entries()){
                for (const [j, comp] of page.comp.entries()){
                    for (const [k, item] of comp.items.entries()){
                        if (item.itemData !== undefined) {
                            
                        } else {

                        }
                    }
                }
            }

Once I have extracted the itemData, I need to insert it into a new array while preserving the original nested structure without any extra key-value pairs.

Expected Output:

{ "page": [ { "comp": [ { "items": [ { "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" }} ] }] }, { "comp": [ { "items": [{ "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" } }] }, { "items": [{ "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" } },{ "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" } }] }] }, { "num": "3” }] }

Answer №1

Why not consider updating the inner loop in a different way instead of using

for (const [k, item] of comp.items.entries()) {...}
:

comp.items = comp.items.map(item => ({ itemData: item.itemDate }));

This will essentially replace each object in the comp.items array with a new object containing only the desired key.

If you prefer to create a new data structure without modifying the original one, you can try something like this:

const filtered = {
  ...this.testingAnimation,
  page: this.testingAnimation.page.map(page =>
    'comp' in page
      ? {
        ...page,
        comp: page.comp.map(comp =>
          'items' in comp
            ? {
              ...comp,
              items: comp.items.map(item => ({ itemData: item.itemData }))
            }
            : comp
          )
      }
      : page
  )
}

Please note that this solution does not utilize Object.entries(). If you wish to do so, use the standard-compliant Object.entries(someObject) as opposed to someObject.entries(), which is generally not defined. Additionally, when dealing with arrays, it's often more appropriate to use someArray.forEach(...) or

newArray = someArray.map(item => ...)
. For further assistance, refer to MDN.

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

Determine using Lodash whether there is an object in an array that matches the ID from a separate array

There is a user array defined as follows: var users = [{ id: 1, name: 'ABC', isDisplay: true }, { id: 2, name: 'XYZ', isDisplay: true }, { id: 3, name: 'JKL', isDisplay: true }]; Additionally, there is another arra ...

The ng-controller directive fails to function on the content of Kendo tabstrip tabs

My ng-controller is not functioning properly for the kendo tabstrip tab content. Could you please review my code below? <!--tabstripCtrl.js--> angular.module('tabstripApp',[]); var app = angular.module('tabstripApp'); app.con ...

Transferring files and information using the Fetch API

I am currently working on a React application and I have defined the state of my application as shown below: const [book, setBook] = useState({ title: '', cover: {} numberPages: 0, resume: '', date: date, }); The & ...

I am attempting to transmit an Error Object through an Axios POST request, but the server is receiving an empty Object

Hey everyone, I'm currently working on creating a Logging Microservice specifically for capturing frontend errors. The goal is to log all errors in a specific format like the example below: catch(err){ sendToLogs({message: 'Could not read input ...

What is the best way to utilize $(target) within a directive?

I created a custom directive for selecting time using two blocks. The challenge is detecting the target event on specific blocks within the directive's template. Directive Template: <div class='time-picker-container'> <div clas ...

Looking to adjust the HSL of individual colors on a JavaScript canvas, similar to editing in Photoshop?

I'm looking to manipulate the HSL of an image using Javascript. I don't want to apply changes to the entire image at once, but rather target specific color sets like blues and yellows, similar to how it's done in Photoshop. What type of da ...

Angular Igx-calendar User Interface Component

I need assistance with implementing a form that includes a calendar for users to select specific dates. Below is the code snippet: Here is the HTML component file (about.component.html): <form [formGroup]="angForm" class="form-element"> <d ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

What is the most effective way to communicate to my client that attempting to conceal the browser toolbar is an ill-advised decision?

One of my clients has a friend who claims to be conducting 'security testing' and insists that the PHP Zend Framework application I developed for them should implement certain browser-side features: hide the location bar, toolbar, bookmarks, me ...

Click on a specific button within a DataTable row

I am working with a dataTable that fetches data from the database using Jquery. In each row, there are two buttons for accepting or rejecting something. My goal is to make the accept button disappear when rejecting and vice versa. public function displayT ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

Unable to overwrite class in VueJS component

Recently, I've been encountering an issue with over-riding a specific instance of my VueJS Component. Despite my efforts, the component continues to use the default value. The particular value causing trouble is the buttonClass. Interestingly, the ot ...

utilizing array.map() to nest multiple layers of arrays

I am facing a challenge with a JavaScript array structure that contains three top-level objects. Each of these objects has an "teamLineup" array, which in turn holds two more objects named "team". These "team" objects have another array called "starters", ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

When the button is clicked, the ng-click event will trigger the addClass function, but only on the second click

My bootstrap alert has this structure: <div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-if="itemExistsAlert"> <button type="button" class="close" data-dismiss="alert">&times;</button> <p>{{alertM ...

Implementing functionality: Removing a row and applying a CSS class upon button click

Check out the fiddle below: https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/ I need help with creating a remove function and adding a CSS class to a clicked row. 1. When I click on "remove", the clicked row should be deleted. When I click on a row, ...

Developing a trivia game using HTML and JavaScript

I'm in need of some serious assistance with creating a quiz using HTML. My goal is to have a web page where users can visit, take a quiz, and have their responses stored. Unfortunately, I don't have the knowledge or skills required to do this on ...

Show only the populated fields in a user profile with ReactJS

Purpose Showcasing only completed fields. Context In my app, users fill out an application with fields like "early reg fee, early reg date, regular reg fee, regular reg date". After completing all the information and clicking "view profile", they should ...

Converting PHP variables to JavaScript using AJAX and XML communication

In order to gain a deeper understanding, I am determined to tackle this task without relying on jQuery. This means I am willing to reinvent the wheel in order to fully comprehend how it functions. My research has led me to believe that AJAX is the key to a ...