I have the following Object:
我有以下目标:
var obj = { "2014": {}, "2013": {}, "2012": {}, "description": null, "image": null },
objKeys = Object.keys(obj);
//objKeys contains [ "2014", "2013", "2012", "description", "image" ]
I would like to remove the "description" and "image" from the objKeys array in one go if they exists there.
如果objKeys数组中存在“description”和“image”,我想一次性删除它们。
How can I achieve that ?
我怎么才能做到呢?
4 个解决方案
#1
1
You can filter them out like this:
你可以这样过滤它们:
objKeys = objKeys.filter(function(x){ return !/[a-z]/gi.test(x)});
The above uses the fact that other keys are numbers. If you want only description
and image
, then put them in an array and do this:
上面使用的事实是其他键都是数字。如果你只需要描述和图像,然后把它们放在一个数组中,然后这样做:
var removeKeys = ["description","image"];
objKeys = objKeys.filter(function(x){ return !new RegExp(removeKeys.join("|")).test(x)});
#2
2
Are the keys you wish to keep always numeric? I'm assuming they're "years"...
您希望始终保持数字键吗?我假设他们“年”…
objKeys.filter(Number); // ["2012", "2013", "2014"]
#3
1
You can filter them directly using regex.
您可以使用regex直接过滤它们。
objKeys = objKeys.filter(function(k){ return !/(description|image)/gi.test(k)});
#4
1
A small modification to @hutchbat's answer, why two iterations over keys?
对@hutchbat的回答进行了小小的修改,为什么要对键进行两次迭代?
Object.keys is one and filter is another. Here is my code
对象。键是一个,过滤器是另一个。这是我的代码
var objKeys = [];
for(var i in obj) if(!/(description|image)/gi.test(i)) objKeys.push(i);
So it iterates one times and collects required.
它迭代1次并收集所需的数据。
#1
1
You can filter them out like this:
你可以这样过滤它们:
objKeys = objKeys.filter(function(x){ return !/[a-z]/gi.test(x)});
The above uses the fact that other keys are numbers. If you want only description
and image
, then put them in an array and do this:
上面使用的事实是其他键都是数字。如果你只需要描述和图像,然后把它们放在一个数组中,然后这样做:
var removeKeys = ["description","image"];
objKeys = objKeys.filter(function(x){ return !new RegExp(removeKeys.join("|")).test(x)});
#2
2
Are the keys you wish to keep always numeric? I'm assuming they're "years"...
您希望始终保持数字键吗?我假设他们“年”…
objKeys.filter(Number); // ["2012", "2013", "2014"]
#3
1
You can filter them directly using regex.
您可以使用regex直接过滤它们。
objKeys = objKeys.filter(function(k){ return !/(description|image)/gi.test(k)});
#4
1
A small modification to @hutchbat's answer, why two iterations over keys?
对@hutchbat的回答进行了小小的修改,为什么要对键进行两次迭代?
Object.keys is one and filter is another. Here is my code
对象。键是一个,过滤器是另一个。这是我的代码
var objKeys = [];
for(var i in obj) if(!/(description|image)/gi.test(i)) objKeys.push(i);
So it iterates one times and collects required.
它迭代1次并收集所需的数据。