-2

Im trying to map an array to get a specific value and output it in my PodcastList component.

My json (the red underline is what I want to be viewed in PodcastList.js) https://itunes.apple.com/se/rss/toppodcasts/limit=100/genre=1314/explicit=true/json enter image description here This is my Home component:

import React, { Component } from 'react'
import { fetchPopularPodcasts } from './api'
import PodcastList from './PodcastList'

export default class Home extends Component {

  state = {
    podcasts: [],
    loading: true,
  }

  async componentDidMount () {
    const podcasts = await fetchPopularPodcasts();
      this.setState({
            podcasts,
            loading: false,
        })
  }

  render() {
    const { podcasts } = this.state

    return (
      <div className='container'>
                        <PodcastList list={podcasts} />
      </div>
    );
  }
}

This is my PodcastList component

import React from 'react'
import { Link } from 'react-router-dom'
import slugify from 'slugify'

const PodcastList = ({ list }) => {
  return (
        <div className='col-md-12'>
        {list.map((pod) => {
          return (
                    <div className='pod-box'>
            GET THE LABEL?????
                    </div>
        )
        })}
        </div>
  )
}


export default PodcastList;

This is my Api.js

import Feed from 'feed-to-json-promise'

export async function fetchPopularPodcasts () {
  const response = await fetch('https://itunes.apple.com/se/rss/toppodcasts/limit=100/genre=1314/explicit=true/json')
  const podcasts = await response.json()
  return podcasts.feed.entry
}

export async function fetchPodcast (podId) {
  const response = await fetch(`https://itunes.apple.com/lookup?id=${podId}&country=se`)
  const podcasts = await response.json()

  return podcasts.results
}

export async function fetchPodcastEpisodes (feedUrl) {
  const feed = new Feed()
  const episodes = await feed.load(feedUrl)

  return episodes
}
Jonas Alvarson
  • 411
  • 2
  • 6
  • 20
  • Are you just trying to get an array of the values in the label property? Or what specifically do you want your output to look like? – mhodges Sep 25 '18 at 20:08
  • 1
    No, It didn't help that image in order to understand. – Ele Sep 25 '18 at 20:08
  • What do you mean by "map through"? – Scott Sauyet Sep 25 '18 at 20:10
  • Yes exactly @mhodges .. – Jonas Alvarson Sep 25 '18 at 20:10
  • Have you looked at this javascript map function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ? – fnmps Sep 25 '18 at 20:10
  • 1
    It would help if you could create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Scott Sauyet Sep 25 '18 at 20:11
  • 1
    Well assuming your data all conforms to the same structure, you could do `data.map(elem => elem["im:artist"].attributes.label)`, where `elem` is each outer object, and the `["im:artist"].attributes.label` is a fixed path to the value you are looking for on each object – mhodges Sep 25 '18 at 20:12
  • Related, possibly duplicate: https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json – Kevin B Sep 25 '18 at 20:14
  • Ok.. I updated my question, sorry for being neewbie. Im in the learning phase of React, so I have a hard time to describe what in want to accomplish. – Jonas Alvarson Sep 25 '18 at 20:35

2 Answers2

2

To get an array containing the label property of each array item object, you can use Array's map method:

let list = [ /* the contents included in your screenshot */ ]

let newList = list.map(pod => { 
    return pod['im:artist'].attributes.label 
})

Note that because of the way the property 'im:artist' is formatted -- i.e., with a colon -- you'll need to access it using bracket notation.

Also, ensure that list is actually an array using the inspector.

Finally, for your case in PodcastList:

const PodcastList = ({ list }) => {
    return (
        <div className='col-md-12'>
            {
                list.map(pod => {
                    return (
                        <div className='pod-box'>
                            pod['im:artist'].attributes.label 
                        </div>
                    )
                 })
            }
        </div>
    )
}

This assumes all of your React-ness is correct, as in that domain, I'm unfamiliar. (If it's still not working, I would investigate if you need curly braces in your innermost div.)

Also, upon reassessing your code, you'd probably rather use forEach as you're not really trying to create a mapped array; rather, you're trying to gain access to a property for each array element.

krhae
  • 34
  • 4
  • Now I understand! Thanks! :-) And in cases like in my json, where the property im:image contains an array? How can i access that? – Jonas Alvarson Sep 25 '18 at 21:15
  • @JonasAlvarson you would go: pod['im:image'][index], where index is a number representing a position in the array. – krhae Sep 25 '18 at 21:31
0

Your child component would be set up in the same way as the component

import React from 'react'
import { Link } from 'react-router-dom'
import slugify from 'slugify'

const default class PodcastList extends Component {

  _renderList = () => {
    let elem = this.props.list && this.props.list.length > 0
      (this.props.list.map((pod) => {
        <div className='pod-box'>{pod}</div>;
      )});
    return elem;
  }

  render() {
    return (
       <div className='col-md-12'>
        {this._renderList()}
       </div>
    )
  }

export default PodcastList;

esewalson
  • 240
  • 3
  • 2