A server-loaded array with type FilterModel[]
is depicted below:
export type FilterModel = {
title: string;
type: FilterType;
collection: FilterList;
};
export type FilterList = FilterListItem[];
export type FilterListItem = {
id: number | string;
text: string;
key ? : string;
selected: boolean
};
let response: <FilterModel>[] = [];
In addition to that, there exists a default array of objects as shown:
let default: <FilterModel>[] = [];
If the server returns an empty array, I must return the default
array; otherwise, I need to update the response
over the existing default
.
How can this be accomplished?
let default = [{
title: "1",
type: "type1";
collection: [{id: 1, text: "A", selected: true}, {id: 2, text: "B", selected: true}]
}];
let response = [{
title: "1",
type: "type1";
collection: [{id: 1, text: "A", selected: false}, {id: 2, text: "B", selected: true}]
}];
let expected = [{
title: "1",
type: "type1";
collection: [{id: 1, text: "A", selected: false}, {id: 2, text: "B", selected: true}]
}];
Simplifying it further:
I have a fixed list of objects that should be displayed on the page:
let list = [{id: 1, name: "A"}, {id: 2, name: "B", {id: 3, name: "C"}}];
This list is saved on the server and retrieved subsequently. At times, only a part of the list may be saved:
let list2 = [{id: 1, name: "A", selected: true}, {id: 2, name: "B", selected: true}];
In such cases, when obtaining list2
from the server, it needs to be merged with list
to obtain the complete modified list. Hence, list
will always contain a fixed number of objects that are subject to modification.
Last amendment:
let response = {
"filters": [
{
"name": "A",
"selected": true,
"collection": [{id: 1, selected: false}, {id: 2, selected: true}]
},
{
"name": "B",
"selected": true,
"collection": [{id: 1, selected: false}, {id: 2, selected: true}]
}
]
};
let def = [
{
"name": "A",
"selected": false,
"collection": [{id: 1, selected: false}, {id: 2, selected: false}]
},
{
"name": "B",
"selected": true,
"collection": [{id: 1, selected: false}, {id: 2, selected: false}]
}
];
def.forEach((filterDef) => {
response.filters.forEach((filter) => {
if(filterDef.name === filter.name) {
filterDef = filter;
}
});
});
console.log(def);