如何修剪对象的所有拥有(not inherited)属性键/名称?要修剪键名,而不是属性的值。
PS。我发现的最接近的类似问题是有关修整[[property values:javascript : trim all properties of an object
编辑:有人建议将此问题重复。但是,我明确需要只修剪键名,而不是值
:Trim white spaces in both Object key and value recursivelyObject.keys()
或Object.entries()
应该胜任。 const obj = { "a " : 1 , " b " : 2 }
const trimmed = Object.entries(obj).reduce((acc,curr)=>{
let [key,value] = curr
acc[typeof key === "string"?key.trim():key] = value // checking if the key is a string
return acc
},{})
console.log(trimmed) // -> { a: 1, b: 2 } notice the trimmed keys