Retrieving a specific value from a multi-layered array

Struggling with extracting numbers from a nested array in a JSON file and matching them with values in another array? Need to send the matched values to another function but can't seem to figure it out after two days of trying. Any advice or assistance would be greatly appreciated.

For reference, here is the data from my json:

{
  "videos": [
    {
      "id": 1,
      "title": "Lego!",
      "created": 1509804047011,
      "duration": 5,
      "poster": "./videos/small.png",
      "video": "./videos/small.mp4"
    },
    {
      "id": 2,
      "title": "Big Bunny",
      "created": 1507804047011,
      "duration": 62,
      "poster": "./videos/bunny.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 3,
      "title": "Prufu myndband",
      "created": 1505904047011,
      "duration": 3600,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 4,
      "title": "Prufu myndband með löngum texta sem fer í tvær línur",
      "created": 1504904047011,
      "duration": 220,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    }
  ],

  "categories": [
    {
      "title": "New videos",
      "videos": [1, 2]
    },
    {
      "title": "Amazing videos",
      "videos": [1, 3, 4]
    },
    {
      "title": "Funny videos",
      "videos": [2, 3, 4]
    }
  ]
}

Answer №1

To extract the videos from different categories, you can use a simple iteration process:

for(const {name, videosList} of data.categories){
  for(const videoId of videosList){
    const selectedVideo = data.videos.find(video => video.id === videoId);
    //perform actions on selected video
  }
}

If you prefer to retrieve only the videos mentioned in the nested categories:

const videoIds = new Set( data.categories.reduce((acc, list) => acc.concat(list)) );

const filteredVideos = data.videos.filter(video => videoIds.has(video.id));

Answer №2

You can easily iterate through the videos array using the map method in this way:

const ids = data.videos.map(video => video.id);
console.log(ids)

As a result, you'll get an array that includes all the ids from the videos array.

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

The JSON parameter being sent to the filter function in the Podio API appears to be ineffective

I tried sending a POST request from klipfolio to {app_id}/filter/ with a JSON object specified in the body, but no matter what parameters I include in the JSON object, they don't seem to have any effect. I followed the parameters outlined in the Podio ...

What is the best way to incorporate a transition on transform using Styled-components?

I attempted to add a transition on the transform property, but unfortunately, it did not produce any visible changes. I tested other properties such as: background-color, color... and they worked perfectly fine. live code: source code: // styled-compo ...

What steps can you take to ensure that a single-page-application (SPA) is easily searchable within a SharePoint environment

In the process of developing a single-page-application (SPA) with ASP.NET MVC, knouckout, and various other libraries, we have decided to handle routing on the front-end, potentially utilizing crossroads.js. Our use of slickgrid.js allows us to present a w ...

A guide on executing code sequentially in Node.js

Recently, I started exploring node.js and discovered its asynchronous programming feature. However, I encountered a challenge when trying to create a loop that prompts the user for input data repeatedly until the loop ends. Upon implementing the code snipp ...

How can you set a predetermined value for a dropdown menu after populating it with data from a Django database?

I currently have a query in my Views.py file that is used to populate a dropdown menu. The query works properly, but I need it to display a specific value that is stored in a variable based on the user's selection. For example, let's suppose we ...

Using PHP's mysqli function to generate a JSON array

Currently, I am in the process of learning php/mysql to enhance a website that I am constructing. Initially, everything was functioning as intended but there were numerous vulnerabilities and security flaws with minimal error handling mechanisms. To addres ...

"Encountering an Unmatched Route" upon initiating a React Native project using Expo

I've recently delved into the world of React Native and I'm facing an issue while trying to kickstart my React Native app with Expo. Whenever I access Metro Bundler through the Expo Go app, I'm greeted with the message: "Unmatched Route - Pa ...

What is the correct way to serialize and deserialize an array of objects to and from JSON format?

I'm currently working on implementing a friends list feature that needs to be stored in a .json file using Kotlin/Java with libgdx. While Java is also an option for this project. The code I have written for (1) isn't functioning correctly, so ins ...

Steps to resolve the error "Cannot POST /index.html" in Nginx, Express, and NodeJS

While setting up my MERN project on the production server, I encountered an issue. In order to manually type in URLs (like myproject.com/dashboard), I added the line try_files $uri /index.html; to the server section of my Nginx configuration file as recomm ...

Ways to retrieve the scroll position of content within an iframe

I have a webpage with an iframe that loads another webpage. <iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe> I am looking to retrieve the scroll position of the content inside the iframe using Jav ...

Updating ASP Update panel causes unexpected issues with jQuery star rating system

After incorporating an updatePanel into my ListView, I encountered a problem with my rating system. Upon initial page load, everything appears fine using the krajee-star rating library: https://i.sstatic.net/JmWI5.jpg However, during a partial-postback, ...

Can you clarify the purpose of response.on('data', function(data) {}); in this context?

I am curious about the inner workings of response.on("data"). After making a request to a web server, I receive a response. Following that, I utilize response.on("data" ...); and obtain some form of data. I am eager to uncover what kind of data is being p ...

A guide on iterating through a multi-dimensional array in Javascript and organizing the results in a specified sequence

Updated on 18th January, 2021 (refer to bold changes) I'm currently facing difficulties while attempting to iterate through a nested array and then organize the output in a specific order. Can you assist me in finding a solution to make this work or ...

Failure to deliver Server Side Events (SSE) to the client side

I'm currently utilizing the MEAN stack and facing challenges with receiving events from the server side. Despite using EventSource, I am unable to make it work as intended. Although the connection appears to be open, no messages are being received fr ...

Optimal management using an image and an onClick event to trigger a JavaScript function

Which control stands out as the optimal choice for displaying images, executing JavaScript functions without postback, and possibly even changing images on hover? ...

Javascript: Anticipating a Return from an Argument

I am currently working on a function that requires an attribute to respond before proceeding with its process. The function call is structured like this : processResult(getResult()); The issue lies in the fact that the getResult function takes some time ...

Using jQuery for the resizing and repositioning of images fails to function correctly upon initial page load

As someone new to Jquery, I am facing an issue with a Wordpress theme I purchased from Theme Forest. The portfolio section is meant to display as either a masonry or grid layout, but neither option is loading correctly on the first attempt. It seems that t ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...

Based on the alphabet, the first name precedes the last name

Looking for a way to identify students in an array where the first name comes before the last name alphabetically. Need to organize the list in descending order by full name using Underscore.js. Any assistance is appreciated. ...

Can the roundabout be modified to display 5 elements in front instead of the usual 3?

I am currently utilizing the roundabout plugin to create an infinite slider that continuously loops. However, I am facing an issue where I would like to display 5 elements in a row instead of 3. Has anyone attempted this customization before? Here is my p ...