Extracting information from JSON response object

Struggling with processing a JSON response object from an API call using .map() and .filter(). The structure of the data is a bit complex, making it difficult to pinpoint which object to operate on for my desired outcome.

  .then(response => {
    console.log(response); //refer below for data structure
    var dataSourceInfo = response.data.included.filter(
      element => element.type === "DataSource"
    );
    var dataSourceName = dataSourceInfo.map(function(included) {
      return included["name"];
    });
    console.log(dataSourceName);

I'm trying to filter through response.data.included to locate an element by type. Then, I want to map over the filtered result to create a new sorted array. Within one of the included arrays, there exists a specific identifying type called DataSource, like this:

included: [
  {
    id: "2147483604",
    type: "DataSource",
    name: "Some DataSource"
  }, 

After logging the dataSourceName, I noticed that only one expected name appears in the array, and it's solely from the first array. It seems like the mapping process isn't reaching the second data.data. Any suggestions on how I can display both names within the filtered array?

Edit: accurate response object is available in the codesandbox

Answer №1

If I am interpreting your request correctly, you are looking for a flat list of names where the type is "DataSource" given an input structured like this:

const response = {
  data: [
    {
      data: {
        data: {
          included: [
            { type: 'DataSource', name: 'First' },
            { type: 'Blah', name: 'Second' },
            { type: 'DataSource', name: 'Third' }
          ]
        }
      }
    },
    {
      data: {
        data: {
          included: [
            { type: 'DataSource', name: 'Fourth' },
            { type: 'Blah', name: 'Fifth' },
            { type: 'DataSource', name: 'Sixth' }
          ]
        }
      }
    },
  ]
}

const result = response.data.flatMap(({data: {data: {included}}}) => 
  included.reduce((memo, {type, name}) => {
    if (type === 'DataSource') {
      memo.push(name)
    }
    return memo;
  }, [])
)

console.log(result)

I have removed irrelevant parts from the response that do not pertain to the issue at hand

Update:

Here is the revised code adapted to function with the responseObject specified in https://codesandbox.io/s/ympo7pr0xx

const responseObject = [ { data: { data: { id: "2147483605", selfUri: "/schedules/2147483605", type: "Schedule", startTime: 1545409610826, status: "InProgress", query: { id: "2147483603", selfUri: "/queries/2147483603", type: "Query" }, dataSource: { id: "2147483604", selfUri: "/datasources/2147483604", type: "DataSource" } }, included: [ { id: "2147483603", selfUri: "/queries/2147483603", type: "Query", name: "Query1", status: "Scheduled", querySchema: { id: "2147483601", selfUri: "/queryschemas/2147483601", type: "QuerySchema" } }, { id: "2147483601", selfUri: "/dataschemas/2147483601", type: "DataSchema", name: "Phone Data" }, { id: "2147483601", selfUri: "/queryschemas/2147483601", type: "QuerySchema", name: "QS1", dataSchema: { id: "2147483601", selfUri: "/dataschemas/2147483601", type: "DataSchema" }, queriesUri: "/queryschemas/2147483601/queries" }, { id: "2147483604", selfUri: "/datasources/2147483604", type: "DataSource", name: "Standalone- 5K", description: "Standalone 5K record" } ] } }, { data: { data: { id: "2147483606", selfUri: "/schedules/2147483606", type: "Schedule", startTime: 1545410049652, status: "Pending", query: { id: "2147483603", selfUri: "/queries/2147483603", type: "Query" }, dataSource: { id: "2147483608", selfUri: "/datasources/2147483608", type: "DataSource" } }, included: [ { id: "2147483608", selfUri: "/datasources/2147483608", type: "DataSource", name: "Standalone 5", description: "Standalone 5 record" }, { id: "2147483603", selfUri: "/queries/2147483603", type: "Query", name: "Query1", status: "Scheduled", querySchema: { id: "2147483601", selfUri: "/queryschemas/2147483601", type: "QuerySchema" }, schedulesUri: "/queries/2147483603/schedules" }, { id: "2147483601", selfUri: "/dataschemas/2147483601", type: "DataSchema", name: "Phone Data" }, { id: "2147483601", selfUri: "/queryschemas/2147483601", type: "QuerySchema", name: "QS1", dataSchema: { id: "2147483601", selfUri: "/dataschemas/2147483601", type: "DataSchema" } } ] } } ];

const result = responseObject.flatMap(({data: {included}}) => 
  included.reduce((memo, {type, name}) => {
    if (type === 'DataSource') {
      memo.push(name)
    }
    return memo;
  }, [])
)

console.log(result)

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

Performing addition in Angular 2 with the help of TypeScript

Here is a code snippet of a component I have written: export class AppComponent { public num1: number = 2; public num2: number = 3; public sum: number = 0; public add() { this.sum = this.num1 + this.num2; } } However, when I r ...

How to stop the mobile keyboard from hiding in JavaScript

On a webpage, I have an HTML setup with an editor and buttons positioned above the keyboard: ------------ |1| Hello | |2| World | | | | | | | ------------ |Tab|( ) [ | ------------ |qwertyuiop| | asdfghkl | | zxcvbnm | | [ ] | ------- ...

What is the best way to retrieve the element at the current cursor position inside an iframe

I'm currently working on a script that is intended to retrieve the element positioned at the cursor's location within an iframe. The code I am attempting to implement should be able to identify the deepest child element at the cursor's posit ...

Having trouble attaching a function to a button click event

My viewModel includes a function: function resetForm(){ loanSystem("lis"); status(""); processor(""); fileType("funded"); orderDate(""); loanNumber(""); team(""); borrower(""); track ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

Setting up JavaScript imports in Next.js may seem tricky at first, but with

Whenever I run the command npx create-next-app, a prompt appears asking me to specify an import alias. This question includes options such as ( * / ** ) that I find confusing. My preference is to use standard ES6 import statements, like this: import Nav f ...

Ways to retrieve the mapState property within a method

Is there a way to access the count property within the method while working with vuex? Take a look at my code provided below: Screenshot of Code: https://i.stack.imgur.com/xNUHM.png Error Message [Vue warn]: Computed property "count" was assigned to bu ...

Is there a way to speed up this sorting function?

Currently, I am sifting through approximately 12,000 users, which amounts to over 1,000 each day. I am using MongoDB with monk and have implemented the following sorting code. class User { constructor(doc) { this.username = doc.username this.kills ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

Generating dynamic arrays in JavaScript

View the working code here: http://jsfiddle.net/sXbRK/ I have multiple line segments with unique IDs, and I know which ones intersect. My goal is to create new arrays that only contain the IDs of the overlapping line segments. I do not need the IDs of l ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

`Incorporate concurrent network requests in React for improved performance`

I am looking to fetch time-series data from a rest service, and currently my implementation looks like this async function getTimeSeriesQuery(i) { // Demonstrating the usage of gql appollo.query(getChunkQueryOptions(i)) } var promises = [] for(var i ...

Can someone provide guidance on incorporating a checkbox into my WordPress site?

I've created a toggle switch and now I want to incorporate it into my website, but I'm unsure of how to do so. The site uses the bbPress plugin on WordPress, and I would like users to be able to click the toggle switch when leaving a comment, wit ...

Is it possible to create a dynamic, live-updating list using Node.js and Firebase?

I am currently working on creating a real-time list using Firebase and Node.js. Below is the code that I have implemented: router.get('/', (req, res) => { db.ref('contacts').on('value', (snapshot) => { const ...

Show information in a horizontal layout, but switch to a stacked arrangement if the screen is too narrow

Is there an optimal way to arrange content side by side when the width allows, like this: [content] [content] [content] [content] If the screen becomes too small, should the content automatically stack like this: [content] [content] [content] I am ...

When importing the Ionic Native File, the JavaScript File object cannot be used simultaneously

When attempting to use the javascript file object, I encountered an issue because the ionic native file object already uses the same key File Here is an example: import { File } from '@ionic-native/file'; @Component({ selector: 'page-ho ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

Remove checked rows in a table with a single click

I have created a table with a list and checkboxes next to each element. There is also a Delete button that I want to connect to the delete operation. Here is the code for the Delete button: <tr id="deleteproject" > <td wi ...

Problem with the authorization of the OAuth2 grant with Google

Utilizing Grant for OAuth2 authentication alongside google. All parameters are provided in config.json : { "server": { "protocol": "https", "host": "thooslo-com-shaunakde.c9.io" }, "google":{ "authorize_url": "https://accounts.google ...