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
Add a ment  | 

2 Answers 2

Reset to default 7

You 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