按索引删除javascript键/值对

时间:2017-02-05 04:06:48

标签: javascript string function object key

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,而不是返回的是原始对象。

对于阅读此内容/愿意提供帮助的任何人,请提前感谢您!

3 个答案:

答案 0 :(得分:2)

你需要这样做:

delete obj[Object.keys(obj)[i]] 

delete Object.keys(obj)[i]以外。现在,您只需删除检索到的值name,而不是name obj的属性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)) 

答案 1 :(得分:1)

你有正确的想法。一个问题是你试图通过索引删除密钥。对象没有与之关联的索引,它们是无序的。这意味着,与列表不同,您不能说object[index],而是说object[key]

您要做的是循环每个,而不是值。然后,您可以查找该值并进行比较,然后使用密钥调用delete

function removeString(obj) {
    var keys = Object.keys(obj);

    for(var i = 0; i < keys.length; i++) {
        if (typeof obj[keys[i]] === "string") {
            delete obj[keys[i]];
        }
    }

    return obj;
}

答案 2 :(得分:0)

Object.keys(obj)将返回obj的所有键的数组(遍历对象的键并将它们(只是键而不是值)复制到结果数组中并返回它)。因此,当您delete该数组的i-th条目时,obj仍然不受影响。要解释更多delete Object.keys(obj)[i],请执行以下操作:

var aCopyOfTheKeys = Object.keys(obj); // get a copy of all the keys of obj
delete aCopyOfTheKeys[i]; // remove the i-th property of aCopyOfKeys 

因此,您不必删除与obj无关的数组条目,而是直接使用delete obj obj[key]的属性这样:

function removeString(obj) {
    // loop through the keys of the object obj
    Object.keys(obj).forEach(function(key) {
        // if the value of this key is of type string
        if (typeof obj[key] === "string")
            // delete it
            delete obj[key];
    });
    return obj;
}

var testObject = {size: 6, name: 'String', age: 20}

console.log(removeString(testObject))