Retrieving data from the array properties in a JSON object

I am facing a challenge with an array of elements, each element is quite complex as it contains nested arrays as properties. My goal is to extract specific attributes from these elements, but I have been struggling to achieve this using the forEach function.

The array is sourced from a JSON file, which is why I am using axios, and the structure of the elements in the array is as follows:

{
    "ITEMS":[
        {
            "id":"0001",
            "name":"foo",
            "sizes":[
                {
                    "name":"small",
                    "id":"9999",
                    "available":"no"
                },
                {
                    "name":"medium",
                    "id":"9998",
                    "available":"yes"
                }
            ]
        },

        {
            "id":"0002",
            "name":"bar",
            "sizes":[
                {
                    "name":"small",
                    "id":"4444",
                    "available":"yes"
                },
                {
                    "name":"medium",
                    "id":"4443",
                    "available":"no"
                }
            ]
        },
        ...
    ]
}

My objective is to extract these attributes and create elements that mimic this model, which will then be pushed into an array:

this.sample = {
    colour:'item.name',
    size:'item.size.name[i]',
    idcode:'item.id',
    sizecode:'item.size.id[i]',
    available:'item.size.available[i]'
}

Here is my attempt so far (but it's not working as expected):

const axios = require('axios');
class IndianaJones {
    constructor(){
        this.sample = {
            name:'',
            colour:'',
            size:'',
            idcode:'',
            sizecode:'',
            available:''
        },
        this.newids = ["10","11","12"...]
        this.freshprods = []
    }

    async FreshProd(){
        for(this.i=0;this.i<this.newids.length;this.i++){
            this.prod = await axios.get(`https://blablabla/${this.newids[this.i]}.json`)
            this.ITEMS.forEach(function(item){
                this.sample.idcode=item.id;
                this.sample.colour=item.name;
                item.sizes.forEach(function(SIZE){
                    this.sample.size=SIZE.name
                    this.sample.sizecode=SIZE.id
                    this.sample.available=SIZE.available
                    this.freshprods.push(this.sample)
                })
            }
            )
        }
        return this.freshprods
    }
}

(async()=>{
    const indiana = new IndianaJones();
    await indiana.FreshProd()
})()

I would greatly appreciate any assistance with this problem. Perhaps utilizing LODASH could be beneficial?

Answer №1

If you want to simplify the structure, you can achieve this by using the Array.flatMap() method or lodash's _.flatMap() function to loop through the ITEMS array, map the sizes array, and create a new object for each size:

const products = {"ITEMS":[{"id":"0001","name":"foo","sizes":[{"name":"small","id":"9999","available":"no"},{"name":"medium","id":"9998","available":"yes"}]},{"id":"0002","name":"bar","sizes":[{"name":"small","id":"4444","available":"yes"},{"name":"medium","id":"4443","available":"no"}]}]};

const simplifiedProducts = products.ITEMS.flatMap(
    ({ id: uniqueId, name: color, sizes }) =>
        sizes.map(item => ({
            color,
            size: item.name,
            uniqueId,
            sizeId: item.id,
            availability: item.available
        }))
);

console.log(simplifiedProducts);

Answer №2

let products = {
    "ITEMS":[
        {
            "id":"0001",
            "name":"shirt",
            "sizes":[
                {
                    "name":"small",
                    "id":"9999",
                    "available":"no"
                },
                {
                    "name":"medium",
                    "id":"9998",
                    "available":"yes"
                }
            ]
        },
        {
            "id":"0002",
            "name":"pants",
            "sizes":[
                {
                    "name":"small",
                    "id":"4444",
                    "available":"yes"
                },
                {
                    "name":"medium",
                    "id":"4443",
                    "available":"no"
                }
            ]
        }
    ]
}

let updatedProducts = [];
products.ITEMS.forEach(function(item){
    item.sizes.forEach(function(SIZE){
        updatedProducts.push({
            idcode: item.id,
            product: item.name,
            size: SIZE.name,
            sizecode: SIZE.id,
            availability: SIZE.available
        })
    })
})
console.log(updatedProducts);

Output

[ { idcode: '0001',
    product: 'shirt',
    size: 'small',
    sizecode: '9999',
    availability: 'no' },
  { idcode: '0001',
    product: 'shirt',
    size: 'medium',
    sizecode: '9998',
    availability: 'yes' },
  { idcode: '0002',
    product: 'pants',
    size: 'small',
    sizecode: '4444',
    availability: 'yes' },
  { idcode: '0002',
    product: 'pants',
    size: 'medium',
    sizecode: '4443',
    availability: 'no' } ]

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

What is the solution to the error message stating that <tr> cannot be a child of <div>?

displayTodos() { return this.state.todos.map(function(item, index){ return <div todo={item} key = {index}>; <tr> <td>{item.todo_description}</td> <td>{item.todo_responsible}</td> ...

Lag in responsiveness of iOS devices when using html5 applications

My HTML5 video app includes a combination of video, a JavaScript swipable playlist, and other animated overlays. When using the app on iOS, the performance of playlist swiping and overlay animations is great upon initial load. However, after playing a vid ...

Encountering issues with integrating an external plugin with AngularJS code

For my app, I am attempting to incorporate intercom for monitoring user activity. It functions correctly when placed inside a script tag in index.html. However, I encounter an error when trying to use it in a .ts file as shown below: app/components/rocket/ ...

I am looking to utilize the JavaScript YouTube API to seamlessly upload a video from my website directly to YouTube

Currently facing an issue with uploading a video from my webpage to YouTube using the JavaScript YouTube API. The error code I'm receiving is "User authentication required" (401). Can anyone provide me with a demonstration example in JavaScript that s ...

External JavaScript functions remain hidden from the HTML page

Having issues with JavaScript functions. I created functions in a separate file named index.js, but when I use them in index.html like "onclick = function()", the file doesn't recognize the function. <!doctype html> <html lang="{{ app()-> ...

Angular Group Formation Issue

I keep encountering the following error: formGroup expects a FormGroup instance. Please pass one in. This is how it looks in HTML: <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> And in my Typ ...

The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child compo ...

Kivy: Issue encountered on iOS while working with JSON file for High Score

I attempted to implement a highscore tracker for an application using a JSON file and the json storage language in Kivy. After importing JSONstore, I included the following code in my main game class: class Game(FloatLayout): highscorejson = JsonStor ...

When submitting the club form, my goal is to automatically generate a club admin within the user list in activeadmin

My dashboard.rb setup looks like this: ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do # form render 'form' # Thi ...

Animating the Three.js Globe camera when a button is clicked

Struggling to create smooth camera movement between two points, trying to implement the function below. Currently working with the Globe from Chrome Experiments. function changeCountry(lat, lng) { var phi = (90 - lat) * Math.PI / 180; var theta = ...

Having trouble accessing news feed with jQuery due to an unexpected token error when attempting to cross domains

I am attempting to access the Yahoo News feed from a SharePoint site, but it is causing a cross-domain access issue. Despite trying various solutions found on numerous websites and blogs, I still cannot resolve the problem. (I am executing this code in the ...

Guide on linking an XML reply to TypeScript interfaces

Currently, I am faced with the task of mapping an XML response (utilizing text XMLHttpRequestResponseType) from a backend server to a TypeScript interface. My approach has been to utilize xml2js to convert the XML into JSON and then map that JSON to the Ty ...

What is the best way to store and retrieve all the variable data from a .js file on a user's device?

I'm looking for a way to save and load multiple variables in JavaScript that determine a "save" state. These variables are stored in a file named "variables.js." Is there a simple method to easily save all the information in this file and then load i ...

What is the best way to modify the appearance of the button?

I'm attempting to change the appearance of buttons at the top of a webpage to be square and blue. I have jQuery code for this purpose, but it doesn't seem to be functioning correctly. Here is the snippet of code I am using: $(document).ready(fu ...

Display the files contained within a folder on the right side of a container by utilizing vue.js

I am currently working on an application that involves a list of folders, each containing various files. The goal is to display these files when a specific folder is chosen. On the left side, users will see a list of folders and on the right side, the resp ...

Are JQuery functions affected when navigating between pages in smart-tables?

Apologies if this question has been answered before or seems obvious. I couldn't find a solution after searching, and as someone new to web development, I might be going in circles here. Issue: I've integrated the smart-table extension () into ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

Manage the information retrieved from a JSON autocomplete query response

I'm receiving the following response from my jquery autocomplete plugin: {"data":{ "events":{"id":"96","value":"Nr 1 Offline","abbrev":"image.jpg"}, "users&q ...

Formatting decimals with dots in Angular using the decimal pipe

When using the Angular(4) decimal pipe, I noticed that dots are shown with numbers that have more than 4 digits. However, when the number has exactly 4 digits, the dot is not displayed. For example: <td>USD {{amount| number: '1.2-2'}} < ...