JSON.stringify 替换程序无法按预期工作(保留名称开头的属性)

问题描述 投票:0回答:2

我想保留以特定字符串开头的所有属性名称,并从对象中删除所有其他属性名称。

为什么以下方法不起作用 - 仅保留属性“foo” - 为什么相反的方法有效? (在这里测试一下):

const o = {foo:1,bar:2,baz:3};
console.log(JSON.stringify(o, (k,v) => k.startsWith('f') ? v : undefined)); // undefined -> why not {"foo":1} ?
console.log(JSON.stringify(o, (k,v) => !k.startsWith('f') ? undefined : v)); // undefined -> why not {"foo":1} ?
console.log(JSON.stringify(o, (k,v) => !k.startsWith('f') ? v : undefined)); // {"bar":2,"baz":3}

Object.keys(o).forEach(key => {
    console.log(key, key.startsWith('f'));
});
// foo,true
// bar,false
// baz,false
javascript stringify
2个回答
0
投票

您需要处理传递给替换函数的空键。

根据文档

替换函数也会被字符串化的初始对象调用,在这种情况下,键是一个空字符串(“”)。然后为要字符串化的对象或数组上的每个属性调用它。数组索引将以字符串形式作为键提供。当前属性值将替换为替换器的返回值以进行字符串化。

因此,当您为第一个条目返回

undefined
值时,字符串化结果为
undefined

console.log(JSON.stringify(o, (k,v) => k.startsWith('f') || k == "" ? v : undefined)); // undefined -> why not {"foo":1} ?
console.log(JSON.stringify(o, (k,v) => !k.startsWith('f') && k != "" ? undefined: v )); // undefined -> why not {"foo":1} ?
console.log(JSON.stringify(o, (k,v) => !k.startsWith('f') ? v : undefined)); // {"bar":2,"baz":3}

0
投票

阅读 JSON.stringify

docs

替换函数也会被字符串化的初始对象调用,在这种情况下,键是空字符串(“”)。

在 JSON stringify 的前两次调用中,当

undefined
不以
key
开头时,您将返回
f
(当
key == ""
时,显然是这种情况)。因此,如果初始对象的替换器返回
undefined
,当然整个字符串化的结果是
undefined

let o = { foo: 3, bar: 4, baz: 5}
let s = JSON.stringify(o, (key, value) => !key 
  ? value 
  : key.startsWith("f") ? undefined : value);
console.log(s);

© www.soinside.com 2019 - 2024. All rights reserved.