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

How can I combine two json arrays in MySQL using a query?

I have a column in my database with a JSON datatype, containing values such as '[1,2,3,4]' and I need to insert additional values like '[5,6]'. After researching, I found out that I can use the concatenate operator '||' for th ...

Harness the power of our custom directive when integrating with x-editable functionality

Is it possible to apply a custom directive to an editable-text element? <span ui-Blur="testfn(price);" editable-text="entry.product_id" e-name="product_id" e-style="width: 200px" e-form="sentryform" e-required> </span> ...

I am having difficulty accessing specific data in JSON using Searchkit's RefinementListFilter

Utilizing searchkit for a website, I am encountering issues accessing previously converted data in json format. The structure of my json directory is as follows: (...) hits: 0: _index: content _type: content _source: ...

Accessing a key from an AJAX JSON response and applying it within a .each() loop in jQuery

I'm struggling with a seemingly simple task that I just can't seem to get right. My goal is to convert multiple text inputs into select fields using AJAX and jQuery. Everything works smoothly, except when trying to make the $.each function dynam ...

Exploring Angular: Utilizing URL Parameters for Multiple States

I am curious to know if it is achievable using angular 1.x. The requirement is to create a responsive application that works well on both mobile and desktop devices. Each page of the application should have a ui-view element that shows the regular content ...

Utilizing lodash and JavaScript for data normalization techniques

Converting data from two dimensions to one dimension using lodash rel href link1 url1 link2 url2 link3 url3 url4 link4 url4 url5 Expected output after normalization rel href link1 url1 link2 url2 link3 url3 link ...

The CSS_MODULES encountered a module build error when utilizing the extract-text-webpack-plugin

While processing CSS with CSS modules in a production environment, I encounter an error, but everything works fine in the development environment. Here is the configuration for webpack.base.js: const path = require("path") const webpack = require("webpac ...

Deleting the v-stepper-header number with Vuetify

I have been searching everywhere in an attempt to resolve this issue, but I have not been able to find a solution. Is there a way to remove the numbers from the v-stepper-header? - Using Vuetify version: 1.5.6 Current: https://i.stack.imgur.com/gLxFX.png ...

What is the best way to decode a JSON object containing geo:point data in PHP?

Similar Question: How to fetch object property with a negative sign? I am attempting to extract information from geo:point / geo:lat but I'm encountering difficulties. Below is the code snippet that I've developed so far $content = get_data ...

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

The hyperlink element has been added but is not clickable

I'm attempting to incorporate a download feature into my webpage using Greasemonkey. Despite successfully adding the new div element to the page, I am encountering an issue where the download window does not open as expected. var iDiv = document.crea ...

Exploring the Latest PHP Popup Upgrade

Hey everyone, I'm currently facing an issue with updating my MySQL database. I have a popup window that is supposed to update it without any errors, but for some reason, it's not actually updating the database. Can anyone help me figure out what ...

Is it considered acceptable to utilize a v-model's value as the basis for an if-statement?

How can I incorporate the v-model="item.checked" as a condition within the validations() function below? <table> <tr v-for="(item, i) of $v.timesheet.items.$each.$iter" > <div> <td> ...

Traversing JSON data in PHP

Currently, I am utilizing json_decode along with TRUE to dissect a JSON response within PHP. Despite my efforts, when attempting to retrieve its elements, I encounter issues. Here is an example of how the response appears: BCLS.secondaryCallResponse({"ite ...

Incorporating an Angular 2 application into HawtIO as a plugin

Can we integrate an entire Angular2 application as a plugin in HawtIO? By doing this, we aim to leverage HawtIO as the main container for our OSGi applications, each with its own user interface, allowing us to easily detect and display each UI web app with ...

How to target and set focus on dynamically generated input field when the ID is unknown

I am facing an issue with a jQuery/AJAX function that loads HTML form elements from the server. The form fields vary, and I want to set focus on the first available input field after the load is complete. I have tried: $(':input:enabled:visible:firs ...

What is the best method for transforming an object into an interface without prior knowledge of the keys

I am looking for a solution to convert a JSON into a TypeScript object. Here is an example of the JSON data: { "key1": { "a": "b" }, "key2": { "a": "c" } } The keys key1 and key2 a ...

Eliminating bottom section in HTML/CSS

I've got this code snippet: new WOW().init(); /* AUTHOR LINK */ $('.about-me-img img, .authorWindowWrapper').hover(function() { $('.authorWindowWrapper').stop().fadeIn('fast').find('p').addClass('tr ...

Upgrading an Express 2.x application to Express 3.0

I am currently studying NodeJs and Express and am in the process of converting a tutorial app from Express 2.5.9 to version 3.0. The following code is now causing an error "500 Error: Failed to lookup view "views/login". How can I update this to render cor ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...