admin管理员组文章数量:1430598
I'm trying to remove properties that are numbers from an object:
function removeNumberValues(obj) {
for (i in obj) {
if (obj['i'] instanceof Number) {
delete obj['i'];
}
}
return obj;
}
I'm trying to remove properties that are numbers from an object:
function removeNumberValues(obj) {
for (i in obj) {
if (obj['i'] instanceof Number) {
delete obj['i'];
}
}
return obj;
}
But it's not removing numerical properties. Halp? What am I missing?
Share Improve this question asked Nov 26, 2017 at 18:23 Advokaten01Advokaten01 651 silver badge4 bronze badges 1- Can you provide a json ? – Akshay Garg Commented Nov 26, 2017 at 18:26
2 Answers
Reset to default 7You need to use the variable i
, not the value 'i'
, and you could check with typeof
operator and number
as value.
function removeNumberValues(object) {
var key;
for (key in object) {
if (typeof object[key] === 'number') {
delete object[key];
}
}
return object;
}
console.log(removeNumberValues({ a: 'foo', b: 42 }));
With Object.keys
and Array#forEach
for iterating the keys.
function removeNumberValues(object) {
Object.keys(object).forEach(function (key) {
if (typeof object[key] === 'number') {
delete object[key];
}
});
return object;
}
console.log(removeNumberValues({ a: 'foo', b: 42 }));
Use typeof
instead. It's more reliable in this case. Unless the value derives from a Number
constructor it's not gonna work.
const obj = {
str: "string",
num: 1,
str2: "string2",
num2: 2
};
console.log(removeNumberValues(obj));
function removeNumberValues(obj) {
Object.keys(obj).forEach(function(key) {
if (typeof obj[key] === 'number') {
delete obj[key];
}
});
return obj;
}
本文标签: javascriptRemove number properties from an objectStack Overflow
版权声明:本文标题:javascript - Remove number properties from an object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745531657a2662089.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论