1

I have one json file and I iterate it with map but I have a deep object key with name 'content' and I want to get specific key from it when I return my json array with map

JSON:

{ "item": [ { "title": "...", "link": "...", "content": { "_url": "How can I get this :D", ... } } ] } 

My javascript code:

getAllNews = async () => { const result = await this.getResource('item/') return result.map(this._transformPosts) // Here I iterate my json } _transformPosts = (item) => { return { title: item.title, link: item.link, image: item.content._url, // and here I try get _url id: item.guide, } } 
7
  • What should the result be? Commented May 30, 2019 at 7:56
  • 1
    You have a typo: item.conten._url Commented May 30, 2019 at 7:56
  • I know it's dont change anything Commented May 30, 2019 at 7:59
  • I want return` content._url` to image ? Commented May 30, 2019 at 8:00
  • 1
    image: (item.content && item.content._url) ? item.content._url : '' should be enough. Commented May 30, 2019 at 8:03

3 Answers 3

1

To correctly handle all cases, remember to always check whether the property effectively exists:

return { title: item.title, link: item.link, image: (item.content && item.content._url) ? item.content._url : '', // <-- fix here. id: item.guide, } 

Possible issues probably were:

  • Typo on your line: item.conten._url, (should be content)
  • item with missing content. In that case, item.content._url would raise an exception. Adding a ternary operator like I did above will ensure the property exists, otherwise it will set the default value to ''. Feel free to change it if that's not the intended default value.
Sign up to request clarification or add additional context in comments.

Comments

0

first of all you have to get item key and It an array. Lets iterate over it and get the key you want to fetch

let jsonData = { "item": [ { "title": "title", "link": "link", "content": { "_url": "How can I get this :D" } } ] } function getKeyFromObject(obj,key){ return obj.item.map(each=>each.content[key]) } const url = getKeyFromObject(jsonData,"_url"); console.log(url);

Comments

0

Try

return { title: item.title, link: item.link, image: item['content']['_url'], id: item.guide, } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.