Reputation: 115
I am trying to show item list ul li. I have two types of input likes array.ul li and I must must support both types. If I give first array type list item should be work or If i give array 2 list item should be work now array 2 is working but If I give array 1 type it's not working.
How to change my code to support both types?
Array 1:
myArray = ["fgtr1",ghyt2","juki3"];
Array 2:
myArray = [
{
mode: 'enable', name: 'ashk'
},
{
mode: 'disable', name: 'qwer'
}
];
Upvotes: 0
Views: 151
Reputation: 4278
The issue here is that the items inside the array are two different types. One is an object with keys and values, and one is strings.
So you have to make some kind of if-statement to check if it is an object or not.
const array1 = ['Test 1', 'Test2', 'Test3'];
const array2 = [
{
action: 'disable',
name: 'Test1'
},
{
action: 'enable',
name: 'Test2'
},
];
public get myArrayInput(): Array<any> {
// If the items inside the array is NOT object, it means it is something else.
return this._myArrayInput.map(item => {
if (typeof item !== 'object') {
return {
action: item,
name: item
};
}
return item;
});
}
If the array is not an object, it will create an object and set the key action
and name
to the value item
.
However, you might want to set a default value to the action, so you could change it from
return {
action: item,
name: item
};
TO
return {
action: 'disable',
name: item
};
Upvotes: 1