javascript - Angular 2: Populate checkbox list comparing two lists and initially check some items -
in angular 2 application in service file 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 call these 2 services separately. once call getuserselection need call both 1 after other if first service success. want compare these 2 json arrays, 1st array includes items, 2nd 1 includes items 1st array. need check items included in 2nd array , add new attribute "selected (true or false)" items of 1st array. ultimately, need return 1 array below.
[{ "key": "test1", "val": 1.0, "selected": false }, { "key": "test2", "val": 1.0, "selected": true }, { "key": "test3", "val": 1.0, "selected": true }]
any suggestions highly appreciated.
you use map function on first array. return new array 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; });
Comments
Post a Comment