删除Array中特定Object内的JavaScript属性

时间:2015-12-15 00:19:21

标签: javascript arrays object iteration

当我执行stringify()时,我有一个看起来像这样的对象:

{"key-1":{"inner_key_obj-1":{"A":"1", "AA":"11", "AAA":"111"}, "inner_key_obj-2":{"B":"2", "BB":"22", "BBB":"222"}, "inner_key_obj-3":{"C":"3", "CC":"33", "CCC":"333"}}, "key-2" : "not-an-object-property" }

我想搜索并删除密钥inner_key_obj-2,以便对象变为:

{"key-1":{"inner_key_obj-1":{"A":"1", "AA":"11", "AAA":"111"},  "inner_key_obj-3":{"C":"3", "CC":"33", "CCC":"333"}}, "key-2" : "not-an-object-property" }

我知道我可以使用delete从对象中删除键及其值,但是如何通过此循环来实现呢?

我做了一些基本测试,例如:

  for (var key in object) 
        {
            if (object.hasOwnProperty(key)) 
            {                
                //Now, object[key] is the current value
                if (object[key] == null)
                { 
                    delete object[type];
                }
            }
        }

......但无济于事。有人可以解释如何通过这个循环吗?

2 个答案:

答案 0 :(得分:2)

    public static int[] copyArray(int [] num){
    int x = 0;
    int numDuplicate = 0;
    int[] copy = new int[num.length]; // we use this to copy the non duplicates
    HashMap<Integer, Integer> count = new HashMap<>(); //hashmap to check duplicates
    for(int i = 0; i < num.length; i++){
        if(count.containsKey(num[i])){
            count.put(num[i], count.get(num[i])+1);
            numDuplicate++; // keep track of duplicates
        }else{
            count.put(num[i], 1); // first occurence
            copy[x] = num[i]; // copy unique values, empty values will be at end
            x++;
        }
    }
    // return only what is needed
    int newSize = num.length - numDuplicate;
    int[] copyNum = new int[newSize];
    for(int i = 0; i < copyNum.length; i++){
        copyNum[i] = copy[i];
    }
    return copyNum;
}


public static void main(String[] args) {
    // sample elements
    int[] nums = new int[20];
    for(int i = 0; i < nums.length; i++){
        nums[i] = (int)(Math.random() * 20);
    }
    System.out.println(Arrays.toString(nums));
    System.out.println(Arrays.toString(copyArray(nums)));

}

做你想做的事吗?

答案 1 :(得分:0)

我只是制作一个新对象

var newObject = {};
for(key in object['key-1']){
    if(key != 'inner_key_obj-2'){
        newObject['key-1'][key] = object[key-1][key];
    }
}

或者

delete object["key-1"]["inner_key_obj-2"];