Using AngularJS Scope to Map an Array within a JSON Array

I'm attempting to extract the type and url values from the media2 object within this JSON array and assign them to an AngularJS scope Array.

"results":[
    {
        "session2":[
            {
                "__type":"Object",
                "about":"about here",
                "attendant2":{
                    "__type":"Relation",
                    "className":"_User"
                },
                "className":"sessionClass",
                "createdAt":"2015-09-16T06:12:54.461Z",
                "media2":[
                    {
                        "__type":"Object",
                        "priority":1,
                        "type":3,
                        "updatedAt":"2015-09-16T06:12:54.153Z",
                        "url":"https://example.com"
                    }
                ],
                "updatedAt":"2015-09-16T06:12:54.461Z"
            }
        ],
        "updatedAt":"2015-10-16T06:08:57.726Z"
    }
]

I have tried using the following code snippets:

$scope.mediaType = results['object'].map(function(item) {
                return item.get('session2')[0].get('media2')[0].get('type');
});

and this

$scope.mediaType = results['session2'].map(function(item) {
            return item.get('media2')[0].get('type');
});

However, I keep receiving

TypeError: results.object is undefined
or
TypeError: results.session2 is undefined
. How can I access the value from that JSON?

Answer №1

the variable "results" is an array, not an object; you can retrieve its contents by accessing it using the notation results[0].session2.map

Answer №2

give this a shot

var data = {
  "info": [{
    "sessionInfo": [{
      "__type": "Object",
      "description": "details here",
      "speakerInfo": {
        "__type": "Relation",
        "className": "_User"
      },
      "className": "sessionInformation",
      "createdAt": "2015-09-16T06:12:54.461Z",
      "mediaContent": [{
        "__type": "Object",
        "priority": 1,
        "format": 3,
        "updatedAt": "2015-09-16T06:12:54.153Z",
        "urlPath": "https://www.youtube.com/watch?v=cVjT1QGilAg"
      }],
      "updatedAt": "2015-09-16T06:12:54.461Z"
    }],
    "updatedAt": "2015-10-16T06:08:57.726Z"
  }]
}


var transformedData = data.info.map(function(item) {
  return {
    format: item.sessionInfo[0].__type,
    url: item.sessionInfo[0].mediaContent[0].urlPath
  }
})
document.write(JSON.stringify(transformedData))

Answer №3

Following the approach suggested in a previous question, I have implemented the following code snippet:

$scope.mediaType = [];
var media2 = results.get('session2')[0].get('media2');

for (i = 0; i < media2.length; i++) {
    $scope.mediaType.push({
        type: session[i].get('type'),
        url: session[i].get('url'),
    });
};

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

Sending back an array within the onOpen function

I am currently in the process of developing a chat application. At this stage, users are able to send messages to each other and I have successfully stored these messages in my database. Now, my objective is to display the stored messages from the database ...

AngularJS directive error: Incorrect function invoked

I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes. module.js var $moduleExample = angular.modu ...

What is the correct way to remove listeners in componentWillUnmount using React, and why is binding necessary in the constructor?

I'm feeling a bit perplexed, can someone explain the distinction between these two snippets of code: constructor(props) { super(props); this.state = { openPane: false } this.togglePaneHelper = this.togglePaneHelper.bind(this); ...

Determine whether the browser tab is currently active or if the user has switched to a different

Is there a way to detect when a user switches to another browser tab? This is what I currently have implemented: $(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // handle double fir ...

What is the CoffeeScript alternative for () => { return test() }?

Currently, I am attempting to write this code in CoffeeScript and finding myself at a standstill... this.helpers({ events: () => { return Events.find({}); } }); ...

Updating ng-src in Angular with image URL from factory/controller promise

Within my application, there is a controller responsible for capturing user input in the form of a Twitter handle. This input is then passed to a factory, which sends it to the backend code to make API calls and ultimately retrieve an image URL. Although ...

Issue: ENOENT error occurred during execution on Docker Container due to missing file or directory '/root/.aws/credentials'

click here for image description While the app runs normally locally, attempting to run it in a Docker container results in an error displayed on the screen. This is my Docker file: FROM node:14.0.0 WORKDIR /app ARG DATABASE_URL ARG AWS_REGION ARG CLIENT_ ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

The appearance of the pop-up mask is displayed at lightning speed

Check out the demo here Here is the HTML code: <div class="x"> </div> <input class="clickMe" type="button" value="ClickMe"></input> This is the JS code: $(".clickMe").click( function() { ...

Multiple executions of Ajax callback detected

I am trying to utilize an ajax-call to a script that searches for numbers. The response is expected to be a json array containing names and surnames as strings. However, I am facing an issue where the script seems to be looping and sending multiple respons ...

Issue with dropdown list functionality in Internet Explorer not functioning correctly

I am experiencing an issue with my dropdown lists. When selecting an item from the first dropdown list, it should not be available in the second dropdown list. To achieve this functionality, I have implemented jQuery code like the following: $(document).r ...

The simple passport.js sign-up feature is not successful as it mistakenly believes that the username is already in

Currently, I am working on setting up a basic signup feature for my Node + Express + Sequelize application using passport.js. The database is empty at the moment, and I am utilizing the passport-local strategy to extract the user's email and password ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

Transforming a solitary JSON object into a JSON array using PHP

i am making a request to coincap.io for a single JSON object {"altCap":282255454377.94916,"bitnodesCount":11508,"btcCap":149160858393,"btcPrice":8830.18849156212,"dom":63.86,"totalCap":431416312770.94904,"volumeAlt":709387849.4057536,"volumeBtc":12537293 ...

Using jQuery to slide elements across the page

I've been attempting to incorporate a sliding effect into my website, but I'm running into an issue where the sliding only occurs on the first click and I can't figure out why. Here is the code snippet I've been using: Html : $("#go ...