简体   繁体   English

修改 Object.fromEntries 的返回值

[英]modify return values from Object.fromEntries

I am trying to modify the values of an object by using .fromEntries() .我正在尝试使用.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!感谢您提前提供任何想法!

在此处输入图片说明


    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)

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.我认为最接近您当前方法的解决方案是首先map ,为要删除的条目返回null ,然后filternull条目以防止Object.fromEntries抛出。 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:如果你想一次性完成,你可以跳过Object.fromEntries并自己将条目reduce到一个对象:

 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, {}) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM