我正在尝试对数组进行过滤以仅获得所需的内容,并且尝试使用filter和reduce进行操作,但无法使其完全正常工作。我正在尝试只获取具有"System.State"
和"oldValue"
和"newValue"
]的对象
const data = { "value": [ { "id": 23, "fields": { "System.State": { "oldValue": "Forecasted", "newValue": "Done" } } }, ] }
问题是
value
数组包含一些可能不具有"System.State"
的对象,而有些具有"System.State"
但仅具有"newValue"
的对象,而不是"oldValue"
和"newValue"
,所以我收到一个许多未定义的错误,我真的不知道该如何处理这些情况。
此示例不具有"System.State"
,另一个不具有"System.State
”,但仅具有"newValue"
:
const data = { "value": [ { "id": 23, "fields": { "System.State": { "oldValue": "Forecasted", "newValue": "Done" } } }, { "id": 24, "fields": { "System.State": { "newValue": "New" } } }, { "id": 25, "fields": { "System.AuthorizedDate": { // This is only an example of an object that does not have System.State "newValue": "2020-03-13T14:14:37.1Z" } } }, ] }
如果有人想知道,我正在使用TFS API。这是我尝试使用过滤器的内容:
data.value.fields.filter(status => status.fields['System.State'].oldValue === 'Forecasted' && status.fields['System.State'] === 'Done')
这是在使用reducer:
const filter = data.value.reduce((c, n) => { const HasNewAndOldValue = c.fields['System.State'].oldValue === 'Forecasted' && c.fields['System.State'].newValue === 'Done'; if (c.fields['System.State'] && HasNewAndOldValue) { return c; } c.push(n); }, []) console.log(data.value.fields && filter);
我做错了什么?顺便说一句,我正在使用
['System.State']
,因为我无法访问带有点的对象属性。
我正在尝试对数组进行过滤以仅获得所需的内容,并且尝试使用filter和reduce进行操作,但无法使其完全正常工作。我正在尝试只获取具有“ System.State”的对象,并带有...
在您的filter
示例中,将data.value.fields.filter()
替换为data.value.filter()
,因为data.value
是一个数组。
此data.value.fields
未定义,您应该通过属性fields
中的每个对象访问属性value
。