Any way how to add current_value from array2 to array1 where is same filter_id ?
array1
const [productsFiltersSlider, setProductsFiltersSlider] = React.useState(undefined);
0: {id: '1', product_id: '28', filter_id: '26', type: 'slider', value: '60'}
1: {id: '2', product_id: '28', filter_id: '25', type: 'slider', value: '5'}
length: 2
array2
const [filteredValuesSlider, setFilteredValuesSlider] = React.useState([{current_value:'', filter_id:''}]);
0: {current_value: '12', filter_id: '25'}
1: {current_value: '63', filter_id: '26'}
length: 2
CodePudding user response:
Try like below:
const productsFiltersSlider = [{ id: '1', product_id: '28', filter_id: '26', type: 'slider', value: '60' }, { id: '2', product_id: '28', filter_id: '25', type: 'slider', value: '5' } ]
const filteredValuesSlider = [{ current_value: '12', filter_id: '25' }, { current_value: '63', filter_id: '26' } ]
filteredValuesSlider.forEach(({
filter_id,
current_value
}) => {
const matchedItem = productsFiltersSlider.find((item) => item.filter_id === filter_id);
matchedItem.current_value = current_value;
})
console.log(productsFiltersSlider);
Since you are using react and you might need to re-render it. Then, do like this:
setProductsFiltersSlider((prevProductsFiltersSlider) => {
const updatedProductsFiltersSlider = [...prevProductsFiltersSlider];
filteredValuesSlider.forEach(({ filter_id, current_value }) => {
const matchedItem = updatedProductsFiltersSlider.find(
(item) => item.filter_id === filter_id
);
matchedItem.current_value = current_value;
});
return updatedProductsFiltersSlider;
});