JavaScript trim 全部拥有 属性 个对象的键名?
JavaScript trim all own property key names of an object?
如何trim所有拥有一个对象的(not inherited)属性键/名称? trim 键名,而不是 属性 的值。
PS。我发现最接近的类似问题是关于 trimming 属性 values:
编辑:这个问题被建议为可能的重复问题。但是,我 明确需要 trim 键名,而不是值 :
据我了解,Object.keys()
或 Object.entries()
应该可以胜任。
const obj = { "a " : 1 , " b " : 2 };
const trimmed = Object.entries(obj).reduce((acc, curr) => {
let [key, value] = curr;
// Checking if the key is a string
acc[typeof key === "string" ? key.trim() : key] = value;
return acc;
}, {});
console.log(trimmed); // -> { a: 1, b: 2 } notice the trimmed keys
您可以测试密钥是否为字符串(而不是 Symbol
) and trim this value and get a new object with Object.fromEntries
const
obj = { "a " : 1 , " b " : 2 },
trimmed = Object.fromEntries(Object.entries(obj).map(([k, v]) => [
typeof k === 'string' ? k.trim() : k,
v
]));
console.log(trimmed);
如何trim所有拥有一个对象的(not inherited)属性键/名称? trim 键名,而不是 属性 的值。
PS。我发现最接近的类似问题是关于 trimming 属性 values:
编辑:这个问题被建议为可能的重复问题。但是,我 明确需要 trim 键名,而不是值 :
据我了解,Object.keys()
或 Object.entries()
应该可以胜任。
const obj = { "a " : 1 , " b " : 2 };
const trimmed = Object.entries(obj).reduce((acc, curr) => {
let [key, value] = curr;
// Checking if the key is a string
acc[typeof key === "string" ? key.trim() : key] = value;
return acc;
}, {});
console.log(trimmed); // -> { a: 1, b: 2 } notice the trimmed keys
您可以测试密钥是否为字符串(而不是 Symbol
) and trim this value and get a new object with Object.fromEntries
const
obj = { "a " : 1 , " b " : 2 },
trimmed = Object.fromEntries(Object.entries(obj).map(([k, v]) => [
typeof k === 'string' ? k.trim() : k,
v
]));
console.log(trimmed);