Property . map cannot access the object correctly

Asked

Viewed 51 times

1

I’m getting information from an object when accessing at certain points, but one in particular is not accessible, situation: When I access the.title item it correctly returns the title value, but when accessing the _url inside content the map returns an error saying it cannot read the "null property"

"item": [
    {
        "title": "Serviço de poda ou corte de árvores precisa de autorização do município",
        "link": "https://g1.globo.com/ms/mato-grosso-do-sul/especial-publicitario/energisa-ms/cidade-das-arvores/noticia/2019/05/22/servico-de-poda-ou-corte-de-arvores-precisa-de-autorizacao-do-municipio.ghtml",
        "guid": {
            "_isPermaLink": "true",
            "__text": "https://g1.globo.com/ms/mato-grosso-do-sul/especial-publicitario/energisa-ms/cidade-das-arvores/noticia/2019/05/22/servico-de-poda-ou-corte-de-arvores-precisa-de-autorizacao-do-municipio.ghtml"
        },
        "description": {
            "__text": "Quem quiser solicitar o serviço pode ir pessoalmente na Central do Cidadão, em Campo Grande O morador que precisa realizar o corte ou poda de árvore, que ofereça risco dentro ou fora da residência, necessita de autorização do município para qualquer intervenção. A espécie é considerada um bem coletivo difuso no Plano Diretor da Cidade e pertence a todos. De acordo com a Secretaria Municipal de Meio Ambiente e Gestão Urbana (Semadur), se a árvore estiver dentro do quintal ou na calçada, nenhum tipo de poda pode ser feito sem a prévia autorização do órgão público. A superintendente de gestão ambiental da Semadur, Gisseli Giraldeli, também explica que o morador tem autonomia para realizar a poda ou corte, desde que a autorização do serviço tenha sido concedida pela prefeitura. Serviço de poda ou corte de árvores precisa de autorização do município Divulgação “A necessidade da intervenção é avaliada por técnicos da prefeitura. Nessa avaliação é feita a verificação do grau de urgência desse trabalho. São incluídos como prioritários aqueles que têm maior grau de risco, já que hoje a demanda é muito grande frente ao recurso que temos para atender”, ressaltou Giraldeli. Ainda conforme a superintendente, em caso de árvores que estão em logradouros públicos, calçadas, canteiros, parques, a prefeitura é a responsável por executar a intervenção. Quem tiver interesse em solicitar o serviço deve comparecer à Central de Atendimento ao Cidadão (CAC), que fica na rua Cândido Mariano, nº 255, no centro de Campo Grande. Para o procedimento é necessário abrir um processo administrativo apresentando documentos pessoais e a localização precisa das árvores. Somente o proprietário do imóvel ou representante legal poderá fazer o requerimento.",
            "__cdata": "\r\n<img src=\"https://s2.glbimg.com/BRe8LbOPe1QUGzQDb7jh7REcMTI=/i.s3.glbimg.com/v1/AUTH_59edd422c0c84a879bd37670ae4f538a/internal_photos/bs/2019/r/Z/ryOg0kS0WpxCBGbryAVQ/imagem.png\" /><br />\r\n"
        },
        "content": {
            "_url": "https://s2.glbimg.com/BRe8LbOPe1QUGzQDb7jh7REcMTI=/i.s3.glbimg.com/v1/AUTH_59edd422c0c84a879bd37670ae4f538a/internal_photos/bs/2019/r/Z/ryOg0kS0WpxCBGbryAVQ/imagem.png",
            "_medium": "image",
            "__prefix": "media"
        },

While writing the editor itself recognizes the _url correctly as an existing string.

Finally running this is the error

Below a snippet with a reduced version of the object demonstrating that the map function finds the link correctly with this JS but when executing in the context of React (which is commented just below the functional) returns reference error

var rssflat = {
		"rss": {
			"channel": {
				"title": "G1",
				"link": [
					"http://g1.globo.com/index.html",
					{
						"_href": "http://pox.globo.com/rss/g1/",
						"_rel": "self",
						"_type": "application/rss+xml",
						"__prefix": "atom"
					}
				],
				"description": "Últimas notícias de economia, política, carros, emprego, educação, ciência, saúde, cultura do Brasil e do mundo. Vídeos dos telejornais da TV Globo e da GloboNews.",
				"language": "pt-BR",
				"copyright": "© Copyright Globo Comunicação e Participações S.A.",
				"image": {
					"url": "https://s2.glbimg.com/veNWQCjPmWVRAfzfLSJt35f_V58=/i.s3.glbimg.com/v1/AUTH_afd7a7aa13da4265ba6d93a18f8aa19e/pox/g1.png",
					"title": "G1",
					"link": "http://g1.globo.com/index.html",
					"width": "144",
					"height": "144"
				},
				"item": [
					{
						"title": "Serviço de poda ou corte de árvores precisa de autorização do município",
						"link": "https://g1.globo.com/ms/mato-grosso-do-sul/especial-publicitario/energisa-ms/cidade-das-arvores/noticia/2019/05/22/servico-de-poda-ou-corte-de-arvores-precisa-de-autorizacao-do-municipio.ghtml",
						"guid": {
							"_isPermaLink": "true",
							"__text": "https://g1.globo.com/ms/mato-grosso-do-sul/especial-publicitario/energisa-ms/cidade-das-arvores/noticia/2019/05/22/servico-de-poda-ou-corte-de-arvores-precisa-de-autorizacao-do-municipio.ghtml"
						},
						"description": {
							"__text": "Quem quiser solicitar o serviço pode ir pessoalmente na Central do Cidadão, em Campo Grande O morador que precisa realizar o corte ou poda de árvore, que ofereça risco dentro ou fora da residência, necessita de autorização do município para qualquer intervenção. A espécie é considerada um bem coletivo difuso no Plano Diretor da Cidade e pertence a todos. De acordo com a Secretaria Municipal de Meio Ambiente e Gestão Urbana (Semadur), se a árvore estiver dentro do quintal ou na calçada, nenhum tipo de poda pode ser feito sem a prévia autorização do órgão público. A superintendente de gestão ambiental da Semadur, Gisseli Giraldeli, também explica que o morador tem autonomia para realizar a poda ou corte, desde que a autorização do serviço tenha sido concedida pela prefeitura. Serviço de poda ou corte de árvores precisa de autorização do município Divulgação “A necessidade da intervenção é avaliada por técnicos da prefeitura. Nessa avaliação é feita a verificação do grau de urgência desse trabalho. São incluídos como prioritários aqueles que têm maior grau de risco, já que hoje a demanda é muito grande frente ao recurso que temos para atender”, ressaltou Giraldeli. Ainda conforme a superintendente, em caso de árvores que estão em logradouros públicos, calçadas, canteiros, parques, a prefeitura é a responsável por executar a intervenção. Quem tiver interesse em solicitar o serviço deve comparecer à Central de Atendimento ao Cidadão (CAC), que fica na rua Cândido Mariano, nº 255, no centro de Campo Grande. Para o procedimento é necessário abrir um processo administrativo apresentando documentos pessoais e a localização precisa das árvores. Somente o proprietário do imóvel ou representante legal poderá fazer o requerimento.",
							"__cdata": "\r\n<img src=\"https://s2.glbimg.com/BRe8LbOPe1QUGzQDb7jh7REcMTI=/i.s3.glbimg.com/v1/AUTH_59edd422c0c84a879bd37670ae4f538a/internal_photos/bs/2019/r/Z/ryOg0kS0WpxCBGbryAVQ/imagem.png\" /><br />\r\n"
						},
						"content": {
							"_url": "https://s2.glbimg.com/BRe8LbOPe1QUGzQDb7jh7REcMTI=/i.s3.glbimg.com/v1/AUTH_59edd422c0c84a879bd37670ae4f538a/internal_photos/bs/2019/r/Z/ryOg0kS0WpxCBGbryAVQ/imagem.png",
							"_medium": "image",
							"__prefix": "media"
						},
						"category": "G1",
						"pubDate": "Wed, 22 May 2019 20:43:20 -0000"
					}
      ]
			},

		}
	}
  
rssflat.rss.channel.item.map((item, i) =>{
      return console.log(item.content._url);
    })
    
//{rssflat.rss.channel.item.map((item, i) =>{
//        return ( 
//				<Card>
//					<img src={item.content._url} alt="Imagem"/>
//					<a href={item.link}>{item.title}</a>
//				</Card>
//				);
//      })
//    }

  • I don’t see anything wrong. You can see in this sandbox that shows the image normally: https://codesandbox.io/s/nervous-dew-od35c

2 answers

0

You are mapping an array of objects, each object is mapped inside "item", so you are trying to access the _url inside the first object, but it only exists inside the second, it is where the error is reversed, if the mapping continued in this way it would try to access . title and . link within each item, would give another error as they only exist in the first.

Summarizing your item gets "{ "title": "Serviço de poda ou corte de árvores precisa de autorização do município", "link": "https://g1.globo.com/ms/mato-grosso-do-sul/especial-publicitario/energisa-ms/cidade-das-arvores/noticia/2019/05/22/servico-de-poda-ou-corte-de-arvores-precisa-de-autorizacao-do-municipio.ghtml", "guid": { "_isPermaLink": "true", "__text": "https://g1.globo.com/ms/mato-grosso-do-sul/especial-publicitario/energisa-ms/cidade-das-arvores/noticia/2019/05/22/servico-de-poda-ou-corte-de-arvores-precisa-de-autorizacao-do-municipio.ghtml" }", as you can see _url does not exist in this json;

A solution would be to put all the properties inside the same object, or not to use map in your item, but to try to access directly, ...item[2].content._url

0


I’m leaving the solution here in case someone else does this kind of inattention to the structure of the object:
The problem was occurring because some objects "item" did not have the object "content", and because I had not done a case treatment he tried to read a property that did not exist, in the snippet there was no error precisely because it has only one object and it has the content, replace the line:

<img src={item.content._url} alt="Imagem"/>

for

<img src={item.content? item.content._url : null} alt="Imagem"/>
  • if that’s the right answer mark it as resolved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.