如何使JavaScript对象的属性可枚举?

xesrikrc  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(124)

我有一个ServiceWorkerRegistration类型的对象,我想将其字符串化:

const reg = await navigator.serviceWorker.register(`https://www.myurl.com/Worker.js`, {scope:"/"});

当我console.log(reg)时,我得到以下结果:

ServiceWorkerRegistration { installing: null, waiting: null, active: ServiceWorker, navigationPreload: NavigationPreloadManager, scope: "https://www.myurl.com/", updateViaCache: "imports", onupdatefound: null, pushManager: PushManager }
active: ServiceWorker { scriptURL: "https://www.myurl.com/Worker.js", state: "activated", onstatechange: null, … }
onerror: null
onstatechange: null
scriptURL: "https://www.myurl.com/Worker.js"
state: "activated"
<prototype>: ServiceWorkerPrototype { postMessage: postMessage(), scriptURL: Getter, state: Getter, … }
installing: null
navigationPreload: NavigationPreloadManager {  }
onupdatefound: null
pushManager: PushManager {  }
scope: "https://www.myurl.com/"
updateViaCache: "imports"
waiting: null
<prototype>: ServiceWorkerRegistrationPrototype { update: update(), unregister: unregister(), showNotification: showNotification(), … }

当我执行typeof reg时得到'object'
但是如果我尝试JSON.stringify(reg),我得到{},同样,如果我尝试做Object.keys(reg),我得到[]
我看了Why does JSON.stringify return empty object notation "{}" for an object that seems to have properties?Why does JSON.stringify on TypeError return an empty object这样的答案,它们声称当对象没有可枚举属性时会发生这种情况。
一个权宜之计是手动打印每个字段,例如console.log(reg["installing"]);,或者手动将每个属性重置为可枚举的,例如每个属性的Object.defineProperty(reg, 'installing', {enumerable: true})
但是,我希望能够执行以下操作:

Object.keys(reg).forEach(key=>console.log(reg[key]));

要做到这一点,对象必须有可枚举的属性。我如何使属性可枚举?

nimxete2

nimxete21#

根据评论,我的工作解决方案是只制作对象的副本(TS中的解决方案):

const objCpy = (obj : any) : string =>{
    let newObj : any = {}
    const keys : string[] = Object.keys(Object.getPrototypeOf(obj));
    keys.forEach((key :  string)=>{
        let val : any = obj[key]
        if(typeof val === "object" && val !== null){
            val = objCpy(val)
        }
        newObj[key] = val;
    })
    return newObj;
}

然后它如预期的那样字符串化:

JSON.stringify(objCpy(reg))
>> `{"installing":{"scriptURL":"http://localhost:3001/Worker.js","state":"installing","onstatechange":null,"onerror":null},"waiting":null,"active":null,"navigationPreload":{},"scope":"http://localhost:3001/","updateViaCache":"imports","onupdatefound":null,"pushManager":{}}`

相关问题