Home > Net >  How to update an object value in array of objects when the keys are same
How to update an object value in array of objects when the keys are same

Time:06-23

I have an Array of objects and one object

const filterArray = [{bestTimeToVisit: 'Before 10am'}, {bestDayToVisit: Monday}]

This values are setting in a reducer and the payload will be like {bestTimeToVisit: 'After 10am'} or {bestDayToVisit: Tuesday}.
So what I need is when I get a payload {bestTimeToVisit: 'After 10am'} and if bestTimeToVisit not in filterList array, then add this value to the filterList array.
And if bestTimeToVisit already in the array with different value, then replace the value of that object with same key

CodePudding user response:

if(filterArray.hasOwnProperty("bestTimeToVisit")) {
filterArray["bestTimeToVisit"] = payload["bestTimeToVisit"];
} else {
filterArray.push({"bestTimeToVisit": payload["bestTimeToVisit"]});
}

CodePudding user response:

I convert the object array into a regular object and then back into an object array. makes things less complicated. I'm making the assumption each object coming back only has one key/value and that order doesnt matter.

const objectArraytoObject = (arr) =>
  arr.reduce((acc, item) => {
    const key = [Object.keys(item)[0]];
    return { ...acc, [key]: item[key] };
  }, {});

const newValues = [{ someKey: 'something' }, { bestDayToVisit: 'Tuesday' }];

const filterArray = [
  { bestTimeToVisit: 'Before 10am' },
  { bestDayToVisit: 'Monday' },
];

const newValuesObj = objectArraytoObject(newValues);
const filterObj = objectArraytoObject(filterArray);

const combined = { ...filterObj, ...newValuesObj };
const combinedToArray = Object.keys(combined).map((key) => ({
  [key]: combined[key],
}));

console.log(combinedToArray);

CodePudding user response:

Need to iterate over the array and find objects that satisfy for modification or addition if none are found.

  function checkReduced(filterrray,valueToCheck="After 10am"){
  let isNotFound =true;
  for(let timeItem of filterrray) {
      if(timeItem.bestTimeToVisit && timeItem.bestTimeToVisit !== valueToCheck) {          
          timeItem.bestTimeToVisit=valueToCheck;
          isNotFound=false;
          break;
      }    
  }
  if(isNotFound){filterrray.push({bestTimeToVisit:valueToCheck})}  
    
}
const filterArray = [{bestDayToVisit: "Monday"}];
checkReduced(filterArray,"After 9am");//calling the function
  • Related