使用键数组过滤Javascript对象 [英] Filtering Javascript object using array of keys
问题描述
基本上,我有一个如下所示的JavaScript数组:
Basically, I have JavaScript array that looks like this:
var keyFilters = ["key_1", "key_2", "key_3"];
我有一个看起来像这样的对象:
And I have an object that looks like this:
myObject["key_1"] = "Value 1";
myObject["key_2"] = "Value 2";
myObject["key_random"] = "Value 2";
我需要配对我的 myObject
对象以仅具有 keyFilters
数组中存在的键.有时,对象将没有过滤器中存在的键.在此示例中,针对 keyFilters
过滤 myObject
将导致以下输出对象:
I need to pair down my myObject
object to only have the keys that exists in the keyFilters
array. Sometimes, the object won't have a key that exists in the filter. In this example, filtering myObject
against keyFilters
would result in this outputted object:
myObject = {
"key_1": "Value 1",
"key_2": "Value 2",
}
我知道JS中没有用于对象的 map
函数,但是有一个用于数组的函数.最好使用该方法还是只编写一次函数来遍历数组,然后遍历对象,然后推送到仅具有匹配键的新对象,或者有某种简化方法?
I know there is no map
function for objects in JS, but there is one for arrays. Would it be best to use that or just write a single-off function for iterating over the array and then over the object, and push to a new object that only has the matching keys, or is there some slicker way?
推荐答案
for (i in myObject) if (keyFilters.indexOf(i) < 0) delete myObject[i];
这篇关于使用键数组过滤Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!