在编写测试时,我JSON.stringify
所有输入并将它们作为键分配给一个对象,然后为该键分配实际值,如下所示:
测试[JSON.stringify(test)] = test
问题是 JSON.stringify({color: undefined})
= {}
就像 JSON.stringify({})
= {}
有人对修改或不同的方法有想法吗?
最佳答案
如果您不能更改属性或使用 undefined
以外的东西初始化它们,那么使用 replacer像这样将它传递给 stringify
:
var obj = {key: "value", color: undefined, other: null};
// this function will be run over all key-value pairs in the object
function replacer(key, value) {
if(value === undefined) // if the value is undefined
return 'undefined'; // then return a string 'undefined' (or null if you want)
return value;
}
// then pass replacer as second parameter to stringify
var str = JSON.stringify(obj, replacer);
console.log(str);
关于javascript - 如果属性未定义,如何将对象写为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238658/