简体   繁体   English

Javascript - 从数组中过滤对象

[英]Javascript - Filtering Objects out of Array

I'm running into an issue where when I pull information into my array "const testOutput", when I go to filter, the filter causes nothing to return.我遇到了一个问题,当我将信息拉入我的数组“const testOutput”时,当我对 go 进行过滤时,过滤器不会导致任何返回。 I think the issue is the "serverArray:" that appears within my array.我认为问题是出现在我的数组中的“serverArray:”。 Here's my code now.这是我的代码。

 const testOutput = { "serverArray": [{ "machineName": "test1", "status": "ACTIVE", "daysActive": 3, "daysLeft": 117 }, { "machineName": "test2", "status": "ACTIVE", "daysActive": 2, "daysLeft": 118 }, { "machineName": "test3", "status": "ACTIVE", "daysActive": 3, "daysLeft": 117 } ] } console.log(Object.values(testOutput).filter(filtered => filtered.daysActive === 3));

When I take out the "serverArray:" within javascript fiddle online, it filters correctly.当我在线取出 javascript 小提琴中的“serverArray:”时,它会正确过滤。 So I was curious if there was something I could add to my filter to remove the "serverArray" so that the objects can be filtered.所以我很好奇是否可以在过滤器中添加一些东西来删除“serverArray”,以便过滤对象。 Thanks!谢谢!

You need to destructure the serverArray array from the testOutput , filter it, and re-assign it.您需要从testOutput解构serverArray数组,对其进行过滤并重新分配。 I added an additional property to the testOutput object in order to demonstrate "keeping" other existing properties.我向testOutput object 添加了一个附加属性,以演示“保留”其他现有属性。

 const testOutput = { "foo": "bar", "serverArray": [{ "machineName": "test1", "status": "ACTIVE", "daysActive": 3, "daysLeft": 117 }, { "machineName": "test2", "status": "ACTIVE", "daysActive": 2, "daysLeft": 118 }, { "machineName": "test3", "status": "ACTIVE", "daysActive": 3, "daysLeft": 117 }] } const { serverArray, ...rest } = testOutput; const filteredOutput = {...rest, serverArray: serverArray.filter(({ daysActive }) => daysActive === 3) }; console.log(filteredOutput);
 .as-console-wrapper { top: 0; max-height: 100%;important; }

Replace testOutput To testOutput.serverArraytestOutput替换为testOutput.serverArray

Try尝试

console.log(Object.values(testOutput.serverArray).filter(filtered => filtered.daysActive == 3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM