繁体   English   中英

循环 object javascript

[英]Loop through object javascript

这是我的响应体。 我只想将 select 协作者的“supportNotifications”键值设置为 true,我该怎么做?

{
  "status": true,
  "date": "2022-04-06T16:33:13.630Z",
  "data": {
    "collaborators": [
      {
        "name": "Paul",
        "lastCheckin": "2022-03-31T19:54:50.584Z",
        "sales": 1,
        "createdAt": "2022-03-30T14:47:48.478Z",
        "id": "62446d4ab7f4da001e8f40dc",
        "supportNotification": true,
        "collaboratorId": 1
      },
      {
        "name": "John",
        "lastCheckin": null,
        "sales": 0,
        "createdAt": "2022-03-01",
        "id": "62446ea4b7f4da001e8f40df",
        "supportNotification": false,
        "collaboratorId": 6
      }
    ],
    "count": 2
  }
}
let response = {
  "status": true,
  "date": "2022-04-06T16:33:13.630Z",
  "data": {
    "collaborators": [
      {
        "name": "Paul",
        "lastCheckin": "2022-03-31T19:54:50.584Z",
        "sales": 1,
        "createdAt": "2022-03-30T14:47:48.478Z",
        "id": "62446d4ab7f4da001e8f40dc",
        "supportNotification": true,
        "collaboratorId": 1
      },
      {
        "name": "John",
        "lastCheckin": null,
        "sales": 0,
        "createdAt": "2022-03-01",
        "id": "62446ea4b7f4da001e8f40df",
        "supportNotification": false,
        "collaboratorId": 6
      }
    ],
    "count": 2
  }
};

const collaborators = response.data.collaborators.filter(c => c.supportNotification);

这将为您提供每个具有 supportNotification = true 的协作者 object。 这是您尝试 select 的结果吗?

var body = {
  status: true,
  date: "2022-04-06T16:33:13.630Z",
  data: {
    collaborators: [
      {
        name: "Paul",
        lastCheckin: "2022-03-31T19:54:50.584Z",
        sales: 1,
        createdAt: "2022-03-30T14:47:48.478Z",
        id: "62446d4ab7f4da001e8f40dc",
        supportNotification: true,
        collaboratorId: 1,
      },
      {
        name: "John",
        lastCheckin: null,
        sales: 0,
        createdAt: "2022-03-01",
        id: "62446ea4b7f4da001e8f40df",
        supportNotification: false,
        collaboratorId: 6,
      },
    ],
    count: 2,
  },
};

var result = [];

body.data.collaborators.forEach((item) => {
  if (item.supportNotification === true) {
    result.push(item);
  }
});

console.log(result);

暂无
暂无

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

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