首页 > 解决方案 > filtering item that has nested objects based on condition and returning the item

问题描述

I have a status list array from an api & i want to filter out the service that has stopped, so if 'online' I want to return the item in console or state. how can I achieve this? can someone tell me what i'm doing wrong. here is my code -

const statusList = [
  {
    "pid": 0,
    "name": "dailyScripts.job",
    "pm2_env": {
      "namespace": "default",
      "kill_retry_time": 100,
      "windowsHide": true,
      "username": "u4011",
      "treekill": true,
      "status": "stopped"
    },
    "pm_id": 0,
    "monit": {
      "memory": 0,
      "cpu": 0
    }
  },
  {
    "pid": 1,
    "name": "finn.job",
    "pm2_env": {
      "namespace": "default",
      "kill_retry_time": 100,
      "windowsHide": true,
      "username": "u3411",
      "treekill": true,
      "status": "online"
    },
    "pm_id": 1,
    "monit": {
      "memory": 0,
      "cpu": 1
    }
  }
]

const data = statusList.filter(service => Object.keys(service.pm2_env.status) === 'online');
console.log(data, 'data');

标签: javascriptreactjsecmascript-6

解决方案


The Object.keys() call is not necessary here, without it, the filter() result should be as you expect:

const statusList = [ { "pid": 0, "name": "dailyScripts.job", "pm2_env": { "namespace": "default", "kill_retry_time": 100, "windowsHide": true, "username": "u4011", "treekill": true, "status": "stopped" }, "pm_id": 0, "monit": { "memory": 0, "cpu": 0 } }, { "pid": 1, "name": "finn.job", "pm2_env": { "namespace": "default", "kill_retry_time": 100, "windowsHide": true, "username": "u3411", "treekill": true, "status": "online" }, "pm_id": 1, "monit": { "memory": 0, "cpu": 1 } } ]

const data = statusList.filter(service => service.pm2_env.status === 'online');
console.log(data, 'data');


推荐阅读