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

Using Vue.js to create dynamic routes that fetch and utilize a unique parameter ID

user/index.vue <tbody> <tr v-for="item in items" :key="item.id" > <td v-if="false" v-text="item.id" /> <td v-text="item.name" /> ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

Is there any re-rendering optimization feature in Angular 2?

After experimenting with React for a few months, I've noticed that it doesn't just re-render a component entirely. Instead, it identifies the differences and updates only those parts. Does Angular 2 operate in a similar manner? Additionally, whe ...

I can't seem to figure out why I constantly struggle with adding a check mark to a checkbox using

Take a look at the code I've provided below : HTML : <input type="checkbox" name="xyz[1][]" id="sel_44" style="margin:2px;" value="12345" onclick="myClick(this)"> Javascript : <script> $('#sel_44').attr("checked", true); < ...

What benefits does registering a Vue component locally provide?

According to the Vue documentation, global registration may not always be the best option. The documentation states: Global registration is not always ideal. When using a build system like Webpack, globally registering all components can result in unnece ...

I am facing an issue with effectively passing properties from a parent state to its child component

In the Login component, I set the authentication state using the token as false initially. After a successful login, the token is changed to true. function Login() { const [user, setUser] = useState({ name: '', email: '' }); const [ ...

What is the process of generating an array of coordinates?

I'm currently working on implementing a geo location search feature in my nodejs backend using mongodb as the database. To achieve this, I receive values from the front end and use map getbound to retrieve viewport data. Below are the variables contai ...

Looking for a way to implement jQuery tabs with restrictions that only allow one tab to be active at a time while using an

In my database table, there are 4 different statuses stored in the status column - 1, 2, 3, and 4. I am looking to implement jQuery tabs or Javascript tabs with tab names as Tab A, Tab B, Tab C, and Tab D. Depending on the status retrieved from the contro ...

`CSS animation for vanishing line effect`

I want to create an animated logo that gives the illusion of being pulled up by a rope, represented by a vertical black line, from the bottom of the page to the top. As the logo moves upwards, I would like the rope to disappear behind it, but I'm uns ...

Combining two arrays of objects in JSON files based on a shared key

Seeking assistance to merge two object arrays in JavaScript/jQuery based on a common key (code). These arrays are sourced from separate JSON files. I've provided shortened versions of the files as they are lengthy. Appreciate any help in advance. O ...

NodeJS API integration failure during ReactJs login attempt

Currently, I am tackling a small project on implementing user login functionality in ReactJs with Nodejs and Express-session. The issue I am facing is that my front end (React login page) isn't functioning properly. Below is the Fetch API code snippet ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

Guide to Developing Functions Using Two-Dimensional Arrays

I'm encountering some challenges when it comes to creating a method that involves a 2D array. While I grasp the concept of creating methods and working with 2D arrays individually, I find it difficult to merge the two together. My task is to generate ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

Having difficulty retrieving data when running a React JS app on the IP address 192.168.XX.XXX

I'm attempting to retrieve backend data in a React app using the Fetch API. It's functioning correctly when I run the React app on localhost, but if I change the address from localhost to an IP, it stops working and displays Unhandled Rejection ( ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Navigating items with Vuetify and V-Virtual-Scroll: A guide to programmatically scrolling into view

Given that I have the height of my item and its position in the list, it should be possible for me to determine the scroll position. Still, I am uncertain about how to actually adjust the scroll position. ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

What is causing the inability to successfully copy and paste Vega editor specs locally?

I successfully executed this spec in Vega Editor: { "$schema": "https://vega.github.io/schema/vega/v3.0.json", "width": 1, "height": 1, "padding": "auto", "data": [ { "name": "source", "values": [ {"name": "Moyenne","vo ...