modify return values from Object.fromEntries

1.4k Views Asked by At

I am trying to modify the values of an object by using .fromEntries(). As you can see in the picture below, I am literally returning a modified Array of hours, but after the function ends, it returns the complete Array, instead of the updated one.

Thank you for any ideas in advance!

enter image description here


    let filteredDates = Object.fromEntries(Object.entries(slots).filter(([slot, value]) => {
        let result = datesArray.some(filterdates => {
            return filterdates.some(filter => slot === filter)
        })
        let currentDay = slot === day ? value.filter(time => time >= currentHour) : null
        result = currentDay ? currentDay : result ? value : result
        console.log("result",result)
        return result
    }))
    
    console.log("filteredDates",filteredDates)
1

There are 1 best solutions below

1
On

I think the closest solution to your current approach is to map first, returning null for the entries you want to delete, and then filter out the null entries to prevent Object.fromEntries from throwing. In code:

const myObj = { "a": 1, "b": 2, "c": 3 };

// Your modification
const doubleWithoutB = ([ key, value ]) => 
  key === "b"            // This is your filter logic
    ? null
    : [ key, value * 2 ] // Here's your map operation
    

console.log(
  Object.fromEntries(
    Object
      .entries(myObj)
      .map(doubleWithoutB)
      .filter(kvp => kvp !== null) // Get rid of the null kvps
  )
)

If you want to do it in one pass, you could skip Object.fromEntries and reduce the entries in to an object yourself:

const myObj = { "a": 1, "b": 2, "c": 3 };

// Your modification
const reduceDoubleWithoutB = (acc, [ key, value ]) => 
  Object.assign(
    acc,
    key === "b" 
      ? {}
      : { [key]: value * 2 }
  )
    

console.log(
  Object
    .entries(myObj)
    .reduce(reduceDoubleWithoutB, {})
)