![](/img/trans.png)
[英]filter through deeply nested object array with array of values in javascript
[英]JavaScript - Filter Object from criteria array, by deeply nested object key?
過去幾天我一直在努力實現以下功能:
我有一個傳入的 object,它有一個嵌套的子對象,它是一個日期列表。 我想根據一系列日期過濾原始 object,並返回修改后的過濾 object,僅包含指定的日期。
這是所需的功能:
let incomingObject = {
'one': {
id: "one",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }],
"2021-05-02": [{ a: "foo", b: "bar" }] } },
'two': {
id: "two",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }, { a: "foo2", b: "bar2" }],
"2021-05-02": [{ a: "baz", b: "far" }] } },
'three': {
id: "three",
dates: {
"2021-05-03": [{ a: "foo", b: "bar" }],
"2021-05-02": [{ a: "foo", b: "bar" }] } } };
// Function to get an array between two dates
const getDaysArray = function (s, e) {
for (var a = [], d = new Date(s); d <= new Date(e); d.setDate(d.getDate() + 1)) {
a.push(new Date(d));
}
let aStrings = a.map((date) => date.toISOString().slice(0, 10));
return aStrings;
};
我不知道如何實現這個 function,它將返回“過濾”的 object:
filterResults(incomingObject, getDaysArray("2021-05-01", "2021-05-01"));
這是期望的結果 - 所有未通過過濾器的(子)對象都被排除在外:
let desiredResult = {
'one': {
id: "one",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }] } },
'two': {
id: "two",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }, { a: "foo2", b: "bar2" }] } } };
到目前為止我的進展:
let dateRange = getDaysArray("2021-05-01", "2021-05-01");
// This logs out only the required keys –– however, logging out the whole "parent" object is completely beyond my comprehension at the moment...
const filteredImages = Object.keys(images).forEach((key) => {
let imgObject = images[key];
Object.keys(images[key].dates).forEach((key) => {
if (dateRange.includes(key)) {
console.log(key);
}
});
});
非常感謝所有幫助或指示!
const incomingObject={one:{id:"one",dates:{"2021-05-01":[{a:"foo",b:"bar"}],"2021-05-02":[{a:"foo",b:"bar"}]}},two:{id:"two",dates:{"2021-05-01":[{a:"foo",b:"bar"},{a:"foo2",b:"bar2"}],"2021-05-02":[{a:"baz",b:"far"}]}},three:{id:"three",dates:{"2021-05-03":[{a:"foo",b:"bar"}],"2021-05-02":[{a:"foo",b:"bar"}]}}}; const getDaysArray = function(e,t){for(var a=[],n=new Date(e);n<=new Date(t);n.setDate(n.getDate()+1))a.push(new Date(n));return a.map(e=>e.toISOString().slice(0,10))} const filterResults = (data, days) => Object.entries(data).reduce((result, [k, v]) => { const {dates, ...rest} = v const filteredDates = days.reduce((acc, date) => { if(v.dates[date]) acc[date] = v.dates[date] return acc }, {}) if (Object.keys(filteredDates).length) result.push([k, {...rest, dates: filteredDates }]) return result }, []) const res = filterResults( incomingObject, getDaysArray("2021-05-01", "2021-05-01") ) console.log(Object.fromEntries(res))
.as-console-wrapper { max-height: 100%;important: top; 0; }
這個如何? 我覺得它非常簡潔和現代:
const filterResults = (data, days) =>
Object.entries(data).reduce((acc, [n, { id, dates }]) => {
const ds = Object.entries(dates).filter(([d,]) => days.includes(d))
return ds.length ? { ...acc, [n]: { id, dates: Object.fromEntries(ds) } } : acc
}, {})
這里的好處是使用嵌套解構模式和擴展運算符來避免樣板代碼。
此外,在對Object.entries
進行reduce
的同時,我們可以直接構造一個 object,而無需中間數組。 在這個實現中,一切都在原始data
數組的一次迭代中完成,因此它的性能更好。
有關片段中使用的技術的其他信息:
匿名 function 的 Lambda 語法(箭頭 function =>
) ;
const filterResults = (data, days) =>
數組和 Object 嵌套參數解構[a, { b, c }]
;
Object.entries(data).reduce((acc, [n, { id, dates }]) => {
使用 Array destructuring [d,]
忽略一些值;
const ds = Object.entries(dates).filter(([d,]) => days.includes(d))
計算屬性名[n]
;
return ds.length? {...acc, [n]: { id, dates: Object.fromEntries(ds) } }: acc
您可以使用數組方法filter()
在您的情況下,它可能看起來像這樣:
const incoming = [ { nested: { date: '2021-05-01' } }, { nested: { date: '2021-03-16' } }, { nested: { date: '2021-02-05' } }, { nested: { date: '2021-01-20' } }, ] let someRange = ['2021-02-05', '2021-03-24'] const result = incoming.filter((item) => { return item.nested.date >= someRange[0] && item.nested.date <= someRange[1] }) console.log(result)
您需要使用filter()
方法將 object 轉換為具有Object.values(yourArray)
的數組。
編輯:
再看一遍你的帖子。 您可以使用Object.keys()
從 object 中檢索密鑰,如下所示:
const dates = { "2021-05-01": [{ a: "foo", b: "bar", }, { a: "foo2", b: "bar2", }, ], "2021-05-02": [{ a: "baz", b: "far", }, ], } const dateKeys = Object.keys(dates) console.log(`Keys from date object: ${dateKeys}`) const result = dateKeys.filter((item) => { return item >= '2021-05-02' }) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.