how to traverse an array with typescript?

1

I have a JSON that contains multiple data which I need to edit, through typescript I found that I can modify it using map

his.items =  this.items.map((item: string) =>

Now inside the item I have a route item.better_featured_image that contains an object but sometimes contains only null, I want to modify it and add the missing route. but apparently I am in an error since the path to be null is no longer an object

this.items =  this.items.map((item: string) => {
     if(item.better_featured_image == null){
      let item.better_featured_image = {}; 
      item.better_featured_image.media_details.sizes.thumbnail.source_url = 'logo-web-color.png';



     }

     return item;
     });

json complete here link

My idea is to create the missing route in the object that contains null

    
asked by Luis Ruiz Figueroa 23.07.2017 в 20:54
source

1 answer

2

The problem is that you are using let , declaring a variable, when what you want to edit is an attribute of the object, it is also necessary to define the attributes that are needed to reach the attribute source_url , your functional code it would look like this:

this.items = json.map((item) => {
     if(item && !item.better_featured_image){
          item.better_featured_image = { 'media_details': {'sizes': {'thumbnail': {'source_url': null}}} };
          item.better_featured_image.media_details.sizes.thumbnail.source_url = 'logo-web-color.png';
     }
     return item;
});

Since we are talking about the image, you could simplify things by leaving only one attribute:

this.items = json.map((item) => {
     if(item && !item.better_featured_image){
          item.better_featured_image = { 'source_url': 'logo-web-color.png' };
     }
     return item;
});

Here I leave you the functional sample! I hope I have been helpful.

Greetings!

    
answered by 24.07.2017 / 01:32
source