function removeString(obj) {
var propertyArray = Object.values(obj); //make array of just properties
for(var i = 0; i < propertyArray.length; i++) {
if (typeof propertyArray[i] === "string") //find string
delete Object.keys(obj)[i]; //delete the key with the same index as the string
}
return obj;//return new object without string
}
var testObject = {size: 6, name: 'String', age: 20}
console.log(removeString(testObject)) //I want {size: 6, age: 20}
我想要上面的函数删除值为string
的字段,而不是返回原始对象。
对于任何阅读本文/愿意提供帮助的人,提前致谢!
最佳答案
你需要做:
delete obj[Object.keys(obj)[i]]
除了删除Object.keys(obj)[i]
。现在,您只需删除检索到的值 name
,而不是 obj
的属性 name
,即 obj["name"]
。这就是为什么它从未从 obj 中删除的原因。这是一个片段示例:
function removeString(obj) {
var propertyArray = Object.values(obj);
for(var i = 0; i < propertyArray.length; i++)
if (typeof propertyArray[i] === "string")
delete obj[Object.keys(obj)[i]]
return obj;
}
var testObject = {size: 6, name: 'String', age: 20}
console.log(removeString(testObject))
关于javascript - 按索引删除 javascript 键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048438/