Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe.

Please review the codesandbox json file first.

The objective is to capture the total calories and nutritive content of this object;

The recipe includes an array of ingredients, with each ingredient containing two items;

Each item consists of various facts (such as vitamins, nutrition, calories, among others);

Every fact has a corresponding value attached to it;

Despite trying multiple nested array.map functions, only able to retrieve calorie values for each item separately due to the nested map function returning each calorie in individual arrays...

The goal is to store the values of each item (recipe stuff item) in separate arrays like:

const vitaminValues = []
const nutritionValues = []
const caloriesValues = []
const othersValues = []

If successful in achieving this structure, total calories, vitamins, nutrients, and other details can be obtained

Any alternative methods or suggestions are welcome :) Thank you!

Here is the JSON file for a sample recipe: https://codesandbox.io/s/relaxed-brown-zrxnr?fontsize=14&hidenavigation=1&theme=dark

Answer №1

let jsonData=//your json data here
let vitaminsData = [];
let nutritionData = [];
let caloriesData = [];
let othersData = [];
let vitaminAData = [];

function extractValuesFromJson(object, array) {
  Object.entries(object).map(
    nutrient => nutrient[1].hasOwnProperty("value") && array.push(nutrient[1].value)
  );
}
jsonData.map(datum =>
  datum.stuffs.map(item =>
    item.item.fact.map(fact => {
      extractValuesFromJson(fact.vitamins, vitaminsData);
      extractValuesFromJson(fact.others, othersData);
      caloriesData.push(fact.calories);
      fact.nutritions.map(nutrition => extractValuesFromJson(nutrition, nutritionData));
      vitaminAData.push(fact.vitamins.A.value);
    })
  )
);
console.log("vitaminsData", vitaminsData);
console.log("nutritionData", nutritionData);
console.log("othersData", othersData);
console.log("caloriesData", caloriesData);
console.log("vitaminAData", vitaminAData);

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

Developing a music playlist using javascript/angular (replicating array elements while linking nested objects)

I am currently working on creating a playlist for a music player within an Angular app that includes a shuffle feature. The actual shuffle function is not the issue, as I am utilizing the Fisher Yates Shuffle method and it is functioning correctly. When th ...

Chained module incorporating a specialized Angular form validation directive

I've been working on incorporating an angular form validation "plugin," but I've hit a roadblock trying to utilize the directive in a child module. As a test, I'm using the HighlightDirective example. @Directive({ selector: '[highligh ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...

Rails : CSS/JavaScript functioning perfectly on local server, facing issues on Heroku deployment

My Rails website features various CSS animation effects and JavaScript elements. While these transitions function smoothly on my local environment, they do not work properly on Heroku. Examining the Heroku logs: 2013-09-17T17:13:36.081145+00:00 app[web.1 ...

Searching for a specific JSON key within a PostgreSQL JSON column

If I have a JSON field called "data" stored in Postgres like the following: { "CUSTA": { "name": "Customer A", }, "CUSTB": { "name": "Customer B", }, "CUSTC": { "name": "Customer C", } } How can I construct ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

Restructure an array of objects into a nested object structure

I have a list of task items that I need to organize into a structured object based on the ownerID var tasks = [ {taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80}, {taskID: "2", title: "task2", ownerID: "110", ownerNam ...

I'm a bit uncertain about the best placement for my progress bar component during the API call

Trying to grasp material ui I managed to implement the progress bar. Struggling with loading it until my data is fully loaded. Uncertain about where to place my progress bar component. Could you guide me on how to resolve this issue during API calls, so I ...

Export data table from HTML to Excel successfully implemented with C#

I am currently working on an Umbraco website and developing a custom plugin for the backend that allows users to export an Excel worksheet from an HTML table. In order to achieve this functionality, I am utilizing AngularJS along with a C# controller. Belo ...

Access to the Express Node.js server is restricted to the machine that is currently hosting the server

I am facing a beginner issue with using express. I am on Ubuntu 14.04 and created a new directory where I ran "express" in the terminal to set up a project template. Following that, I ran "npm install" to install the dependencies. I then made changes to &a ...

What is the simplest method for comparing transaction amounts?

I'm in the process of integrating PayPal into my website using their REST API. My goal is to allow users to input the amount they want to deposit. While I can obtain the total during payment creation, I'm unsure how to smoothly pass it to the exe ...

I have the latitude and longitude for both the shop and user, and I am looking to display a list of shops in order based

Currently, I have the latitude and longitude for both my shop and the user. My objective is to display a list of shops that fall within the geographic area between the user's location and the shop's coordinates using Sequelize ORM. Can you provid ...

Explaining Vue.js actions and mutations in detail

Can someone help clarify the relationship between these functions for me? I'm currently learning about Vue.js and came across an action that commits a mutation. The Action: updateUser({commit}, user) { commit('setUser', {userId: user[&ap ...

What steps can be taken to turn off specific warning rules for CSS mode in ACE editor?

Utilizing the Ace Editor (through Brace and React-Ace) is a key aspect of my project. In our implementation, we specify the editor's mode as "css" and integrate it into our webpage. While this setup functions correctly, we have observed that some of ...

Tips for successfully transferring values or parameters within the Bootstrap modal

How can I create a cancel button that triggers a modal asking "Are you sure you want to cancel the task?" and calls a function to make an API call when the user clicks "Ok"? The challenge is each user has a unique ID that needs to be passed to the API for ...

Constantly encountering crashes with Swifty JSON

Utilizing SwiftyJSON for parsing json responses from the server. Encountering frequent app crashes (reports in crashlytics) but unable to pinpoint the exact location. All reports point towards this line of code: let jsonDict = JSON(data: data, options: ...

Steps for Filling a List Box (combo box) with Data from a Multi-Dimensional Array

As a student learning JavaScript, I have an assignment due tonight and am facing challenges with populating a List Box (combo box) from a Multi-Dimensional Array. After working on the code multiple times, I managed to create a multi-dimensional array that ...

Encountering an issue when trying to send data with Axios client to the child component

I'm encountering an issue while attempting to pass data to a child component for rendering. import axios from 'axios'; import React from 'react'; import MovieCard from './MovieCard'; import { useState, useEffect } from ...