userlkjsflkdsvm
userlkjsflkdsvm

Reputation: 973

Adding object to array which is missing previously - angular 2+ / ionic 2+

I have one array and one object. The array is a single api call. I'm calling the object each time I'm sending an ID. In my old array there is a missing parameter - data. I need to add the data object to this array, by matching imageID and seeing which object doesn't have the data object, assuming by filtering it out then just map through them from there. The issue is I'm having trouble filtering out the old array and only make those calls for the objects that don't have data.

Old

[
{itemID: 10, color: "blue", imageID: "1", data: "somedata"}
{itemID: 11, color: "red", imageID: "2"}
{itemID: 12, color: "green", imageID: "2", data: "somedata2"}
{itemID: 13, color: "green", imageID: "1", data: "somedata"}
]

New - each object is an api call. It takes the imageID of the old array into account.

{imageID: "1", data: "somedata"}
{imageID: "2", data: "somedata2"}

What I want:

[
{itemID: 10, color: "blue", imageID: "1", data: "somedata"}
{itemID: 11, color: "red", imageID: "2", data: "somedata2"}
{itemID: 12, color: "green", imageID: "2", data: "somedata2"}
{itemID: 13, color: "green", imageID: "1", data: "somedata"}
]

Component.ts

this.oldArray.map(res => {

    this.new(res)

  })

new(res){
    this.service.new(res.imageID).subscribe(icon => {
        res.data = 'data:image/png;base64,' + icon.data;
    }
   )
  }

Upvotes: 0

Views: 248

Answers (1)

Chandru
Chandru

Reputation: 11184

Try like this :

ngOnInit() {
    this.oldArray.map(obj => {
        this.news(obj);
    })
}

news(obj) {
    let newObj = { imageID: "2", data: "somedata2" }
    if (!obj.data) {
        if (obj.imageID === newObj.imageID) {
            obj.data = newObj.data;
            console.log('obj', obj);
        }
    }
}

Upvotes: 1

Related Questions