使用 JavaScript 篩選巢狀物件中的鍵
假設我們有一個這樣的物件陣列 −
const arr = [{ 'title': 'Hey',
'foo': 2,
'bar': 3
}, {
'title': 'Sup',
'foo': 3,
'bar': 4
}, {
'title': 'Remove',
'foo': 3,
'bar': 4
}];我們需要編寫一個 JavaScript 函式,該函式將一個這樣的陣列作為第一個輸入,並將一個字串文字陣列作為第二個輸入。
然後,我們的函式應該準備一個新陣列,其中包含所有那些其 title 屬性部分或全部包含在第二個文字陣列中的物件。
示例
程式碼如下 −
const arr = [{ 'title': 'Hey',
'foo': 2,
'bar': 3
}, {
'title': 'Sup',
'foo': 3,
'bar': 4
}, {
'title': 'Remove',
'foo': 3,
'bar': 4
}];
const filterTitles = ['He', 'Su'];
const filterByTitle = (arr = [], titles = []) => {
let res = [];
res = arr.filter(obj => {
const { title } = obj;
return !!titles.find(el => title.includes(el));
});
return res;
};
console.log(filterByTitle(arr, filterTitles));輸出
控制檯中的輸出如下 −
[ { title: 'Hey', foo: 2, bar: 3 }, { title: 'Sup', foo: 3, bar: 4 } ]
廣告
資料結構
網路
關係型資料庫
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP