I have a dropdown select field where I can choose different attributes value. The problem is when I try to store the selected data in the state I got twice the label which I don't need. I want if the label already exists in my state the labels will not include but the selected value will include.
My selected objects:
Expected Output:
{label: "colors"
selected: Array(2)
0: {label: 'Black', value: 1}
1: {label: 'Green', value: 2}
},
{label: "size"
selected: Array(1)
0: {label: 'M', value: 1}
} ]
I am trying like this but am confused about how can I skip the label if the value label already exists.
const previousValue = (label: string, e: any) => {
let isExist: any;
if (newAttributes?.length > 0) {
isExist = newAttributes.find((attr: any) => attr.label === label)
}
console.log(isExist);
const newValue = { label: label, selected: e }
setNewAttributes((oldArray: any): any => {
if (isExist) {
// confused how can I skip the label
} else {
return [...oldArray, newValue]
}
});
}
CodePudding user response:
You could use the method findIndex
instead of find
to find if the item exists in newAttributes
array.
findIndex
returns -1
when item doesnt exist in the array and returns the index of the item otherwise. You could use that index to get the Object and update it.
const previousValue = (label: string, e: any) => {
let itemIndex: any;
if (newAttributes ? .length > 0) {
itemIndex = newAttributes.findIndex((attr: any) => attr.label === label)
}
const newValue = {
label: label,
selected: e
}
setNewAttributes((oldArray: any): any => {
if (itemIndex >= 0) {
// item exists at newAttributes[itemIndex]
let updatedArr = [...oldArray];
updatedArr[itemIndex] = {
...updatedArr[itemIndex],
selected: [...updatedArr[itemIndex].selected, e]
}
return updatedArr;
} else {
return [...oldArray, newValue]
}
});
}