我们必须编写一个函数,该函数接受一个对象和一个字符串常量数组,它返回带有出现在字符串数组中的键的过滤对象。
例如-如果对象是{“ a”:[],“ b”:[],“ c”:[],“ d”:[]}并且数组是[“ a”,“ d”],则输出应该是-
{“a”: [], “d”:[]}
因此,让我们为该函数编写代码,
我们将遍历对象的键,如果它存在于数组中,如果存在,将键值对推入一个新对象,否则,我们将继续迭代并最后返回新对象。
const capitals = { "usa": "Washington DC", "uk": "London", "india": "New Delhi", "italy": "rome", "japan": "tokyo", "germany": "berlin", "china": "shanghai", "spain": "madrid", "france": "paris", "portugal": "lisbon" }; const countries = ["uk", "india", "germany", "china", "france"]; const filterObject = (obj, arr) => { const newObj = {}; for(key in obj){ if(arr.includes(key)){ newObj[key] = obj[key]; }; }; return newObj; }; console.log(filterObject(capitals, countries));
输出结果
控制台中的输出将为-
{ uk: 'London', india: 'New Delhi', germany: 'berlin', china: 'shanghai', france: 'paris' }