I've got a select option in which i put some values depending on an array. For instance we could have something like
[{
name: 'A',
type: 'a',
},
{
name: 'B',
type: 'b',
},
{
name: 'B',
type: 'b',
},
{
name: 'C',
type: 'c',
}]
my select option values are for example
myOptions: any[] = [
{name: 'City', value: 'city'},
{name: 'State', value: 'state'},
{name: 'Region', value: 'region'},
];
now, what I have to do is:
if the array contains all records have type "a", then my options should be myOptions[0].
If the array contains all records have type "b", then my options should be myOptions[1].
If the array contains different records have type, then my options should be myOptions[2].
the array values is variable. the options of the select not. This is the component
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
aArray = [
{
name: 'A',
type: 'a',
},
{
name: 'A',
type: 'a',
},
{
name: 'A',
type: 'a',
},
];
bArray = [
{
name: 'B',
type: 'b',
},
{
name: 'B',
type: 'b',
},
{
name: 'B',
type: 'b',
},
];
difArray = [
{
name: 'A',
type: 'a',
},
{
name: 'B',
type: 'b',
},
{
name: 'B',
type: 'b',
},
{
name: 'C',
type: 'c',
},
];
myOptions: any[] = [
{ name: 'City', value: 'city' },
{ name: 'State', value: 'state' },
{ name: 'Region', value: 'region' },
];
ngOnInit(): void {
this.difArray.every((value, i, array) => {
array.map((x) => {
if (value.type === 'a' && x.type === 'a') {
console.log('a');
} else if (value.type === 'b' && x.type === 'b') {
console.log("b");
} else {
console.log('generic');
}
})
});
}
}
that's the html
<select>
<option [ngValue]="null" disabled selected>test</option>
<option
*ngFor="let option of myOptions; let i = index"
[value]="option.value"
>
{{ option.name }}
</option>
</select>
CodePudding user response:
Try this
this.aArray.forEach((object:any)=>{
if( aArray.name === "a"){
this.option == object[0]
}
else if (aArray.name === "b") {
this.option == object[1]
}
....
})
})
CodePudding user response:
You can use a combination of every
and find
.
If I understand the rule correctly, you have to check that every entry of aArray
can be found in difEntry
, which translates to this :
if (aArray.every(entry => difArray.find(difEntry => difEntry.type === entry.type && difEntry.name === entry.name))) {
console.log('Contains all entries from A')
} else {
console.log('Does not contain all entries from A')
// Repeat with bArray etc
}