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

Nested JSON file retrieval by Axios

I am having trouble retrieving the 'title' from my JSON file. I have been trying to access it through the 'results - metaData' path, but so far without success. The 'resultPacket' is returning data, but accessing 'metaDat ...

Position the text alongside the thumbnail rather than in the center

In the current setup, my username text is positioned in the center of the view. I want to reconfigure it so that it displays directly to the right of the thumbnail. However, removing the alignItems: 'center', property from the item disrupts the e ...

When attempting to initiate a new session, Webdriver.io receives an HTML response from selenium

Currently, I am attempting to execute my selenium tests using webdriver.io. However, the test runner is encountering failure when attempting to establish a session: [18:12:36] COMMAND POST "/session" [18:12:36] DATA {"desiredCapab ...

The error message "Uncaught ReferenceError: req is not defined with [email protected]" indicates that the variable

Discovered a helpful post that seems to address the problems. https://github.com/angular/angular-cli/issues/8359 I'm unsure about the steps to take next to resolve this issue. Can anyone clarify? Could you please advise on which version of Angular ...

modify column data using a JSON object

When attempting to update a field with JSON data in the TEST_TABLE: UPDATE TEST_TABLE SET JSON_DATA = "{ "Business_Type": "载货", "Collected_Article_Quantity": null, "Consignee_Company_ContactPerson": n ...

How can I deliver assets in React without the PUBLIC_URL showing up in the path?

I have set up a portfolio website that includes my resume. I am trying to make it so that when someone visits the route http://localhost:3000/resume.pdf, they can view my resume directly. The resume.pdf file is located in my public folder. However, instead ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

Is there a way to convert a JSON file with a single 'header' row and subsequent 'data' rows, possibly using jq?

I currently have a JSON file structured like this: { "data" : [ { "values" : [ "ColumnHeader1", "ColumnHeader2", "ColumnHeader3" ]}, { "values" : [ "Row1Column1", "Row1 ...

Failure to trigger success function during ajax upload

My upload script features a progress bar to track file uploads. The file successfully uploads to the server and the progress bar is functioning as expected. However, the success function is not being triggered and I am unsure why. There are no errors in ...

Why is it that I am unable to properly encode this URL in node.js?

$node querystring = require('querystring') var dict = { 'q': 'what\'s up' }; var url = 'http://google.com/?q=' + querystring.stringify(dict); url = encodeURIComponent(url); console.log(url); Here is the re ...

Showing Stationary Pictures at Full Size in OpenLayers

I am trying to showcase static images as maps using a StaticImage layer in ol3, with the image size set at 100% in pixels. However, I am facing difficulty in ensuring that the displayed images are always the correct size based on the extent and zoom variab ...

When you scroll through the page, white blocks suddenly appear

After completing a website, I noticed some white blocks appearing when scrolling. You can view the site here. This issue occurs on both mobile and desktop devices during the initial load only. Could this indicate that the page has not fully loaded yet? If ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

leveraging embedded jetty for developing a web-based interface

As a newcomer to web development and using embedded Jetty, I have created the source code below in Eclipse IDE. I need to programmatically start the Jetty server and cannot use the command line to do so. The web interface must be lightweight due to the li ...

"Send the response in ExpressJS before making a request to loop through the

I am currently working with a postgres database that contains records with a column format in JSON, which refers to other similar records. The challenge I am facing is retrieving linked records through asynchronous methods due to the nested structure and ...

Can you show me a way to display a dynamically created array component on an Angular2 template html?

One way I've been able to generate dynamic component instances is by choosing from pre-existing components. For instance, @Component({ selector: 'dynamic-component', template: `<div #container><ng-content></ng-conten ...

Transferring a boolean model value to a JavaScript function triggers a reference to the onchange function

An onchange event is triggered in an input tag of type checkbox, calling a JavaScript function and passing three parameters from the model: <input type="checkbox" ... onchange="changeRow('@Model.Id', '@Model.Type', @Model.AwaitingAp ...

Does this function only function on a singular div?

I need some help! I'm having trouble getting a function to trigger on the divs below the initial one. Any advice? ...

React Big Calendar - Creating a personalized property for a unique perspective

My React Big Calendar library has a custom view for the year. <Calendar localizer={localizer} events={events || []} startAccessor="start" endAccessor="end" defaultView="year" views={{ year: YearView }} c ...