0

In my Angular 2 application in the service file I have following.

service.ts

getUserSelections() {
    return this.http.get('http://localhost:8080/selection/selections').map((res: Response) => res.json());
}

getSavedSelections() {
    let params: URLSearchParams = new URLSearchParams();
    params.set('access_token', localStorage.getItem('access_token'));
    return this.http.get('http://localhost:8080/interest/user/selections', { search: params }).map((res: Response) => res.json());
}

getUserSelections returns following json array.

[{
    "key": "test1",
    "val": 1.0
  }, {
    "key": "test2",
    "val": 1.0
  }, {
    "key": "test3",
    "val": 1.0
  }]

getSavedSelections returns following.

[{
    "key": "test2",
    "val": 1.0
  }, {
    "key": "test3",
    "val": 1.0
  }]

I don't need to call these two services separately. Once I call getUserSelection I need to call both one after the other if first service success. Then I want to compare these two json arrays, 1st array includes all the items, 2nd one includes some items from 1st array. SO I need to check which items are included in the 2nd array and add new attribute as "selected (true or false)" to the items of the 1st array. Ultimately, need to return one array as below.

[{
    "key": "test1",
    "val": 1.0,
    "selected": false
  }, {
    "key": "test2",
    "val": 1.0,
    "selected": true
  }, {
    "key": "test3",
    "val": 1.0,
    "selected": true
  }]

Any suggestions are highly appreciated.

1 Answer 1

1

You could use the map function on the first array. It will return a new array with the callback function called on each item.

let result = Array1.map((elem1) => {
  elem1.selected = false;
  Array2.forEach((elem2) => {
    if (elem2.key === elem1.key)
      elem1.selected = true;
  });
  return elem1;
});
Sign up to request clarification or add additional context in comments.

4 Comments

These two arrays are dynamic
What do you mean ? The key to compare is dynamic ?
JSON array items my be changed
Okay, but it's not a problem, if the key to compare is the same this will work the same. If you need more flexibility you can wrap this snippet in a function that accept a key or array of key to compare ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.