Hi i m trying to get the data from a loop i wrote to go through a object and get some data from there.

my object looks like this

    { 
id:12, 
cities:[london, lisbon, berlin],
images[{id:1, image_urls:abc,},{id:2, image_url:bcd}, {id:3, image_url: cde}], 
status: "published"

}

the function i wrote is to get the image_url data from this object:

 imagesUrlFunction() {
    console.log("array Length");
    console.log(this.images.length);
    let keys = this.images.length;

    for (let n = 0; n < keys; n++) {
      this.imagesUrls = this.images[n].image_url;

      console.log("imageUrlMedia Var");
      console.log(this.imagesUrls);
      // console.log(this.images[n]);
    }
  }

When i console log this.imagesUrls i can get my data, that is my url, and because is in loop i can get all the urls, or at least console log all urls.

My problem is i want to put that that into an object so i can use it with an *ngFor directive, but i cant. I tried to create an empty object and assign imagesUrls to it, but with no sucess.

Can anyone help?

Thanks for your patient, i am just a newbie in javascript and educating my self on it.

  • By object do you mean you want to put the urls in an array by themselves? If not please show an example of what you expect to output – Dominic Jul 9 at 11:06
  • Your object is broken syntactically. – Alex Jul 9 at 11:08
  • The first object in your array has a property image_urls and the others have a property image_url. I assume the s at the end of the first one is just a typo, but you may want to fix that ;) – Archer Jul 9 at 11:12
up vote 1 down vote accepted

declare variable in component;

var images: any[];

ngOnInit(){

    var obj // Logic of get object 

    this.images = obj.images;
}

use images var in view

<div *ngFor="let img of images">
    {{img.image_url}}
</div>

in your component.ts, add

response = {};

this.response =  { 
id:12, 
cities:[london, lisbon, berlin],
images:[{id:1, image_urls:abc,},{id:2, image_url:bcd}, {id:3, image_url: cde}], 
status: "published"

}

in you component.html (if you are using li, or use any as your need )

<li *ngFor="let item of response.images">
     <img src="{{item.image_urls}}" />
</li>
  • Great Man!! This solved My problem. – pedro davim Jul 11 at 14:46

According to my understanding, you are mainly trying to make an array of image urls, You can simply use Array.map() for that :

var obj = { 
  id:12, 
  cities:["london", "lisbon", "berlin"],
  images:[{id:1, image_url:"abc"},{id:2, image_url:"bcd"}, {id:3, image_url: "cde"}], 
  status: "published"
};

var result = obj.images.map((a) => a.image_url);

console.log(result);

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.