简体   繁体   English

使用 javascript 过滤嵌套 object 数组

[英]Filter array of nested object using javascript

I want to filter specific object using nested object element this我想使用嵌套的 object 元素过滤特定的 object

"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"

This my data:这是我的数据:

const data = [
  {
    name: "test",
    token: {
      expiryTime: "2021-09-24T12:27:30.654Z",
      purpose: "ForgotPassword3",
      token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
    },
    user_id: "acaacc940c9ebfe798dee68acf5c",
    zipcode: "",
  },
  {
    name: "df ",
    token: null,
    user_id: "e0efe9810ca289ccd590bce48051",
    zipcode: "",
  },
  {
    name: "Io",
    phone: "88888888",
    state: "NY",
    token: null,
    user_id: "c88ce38d0c86f786c3a4b0f9f967",
    zipcode: "13201",
  },
];

Expected output is: Data array inside the first object of token using filter object. Below given expected out.预期 output 是:使用过滤器 object 的令牌的第一个 object 内的数据数组。下面给出预期输出。

const data = [
  {
    name: "test",
    token: {
      expiryTime: "2021-09-24T12:27:30.654Z",
      purpose: "ForgotPassword3",
      token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
    },
    user_id: "acaacc940c9ebfe798dee68acf5c",
    zipcode: "",
  },
];

If you want a specific object, you could use find instead of filter.如果你想要一个特定的 object,你可以使用find而不是 filter。 find will return the first element which verifies the condition specified to the find method where as the filter method is used to filters all the elements and returns all the element that matches the condition withing an array. find 将返回验证指定给 find 方法的条件的第一个元素,其中filter方法用于过滤所有元素并返回与数组中的条件匹配的所有元素。

  • *You need to add the optional chaining ?. *您需要添加可选的链接?. because the token object might be null like you have in some of your data here both examples:因为令牌 object 可能是 null 就像您在此处的某些数据中所拥有的两个示例一样:

 const data = [ { "name": "test", "token": { "expiryTime": "2021-09-24T12:27:30.654Z", "purpose": "ForgotPassword3", "token": "4f1f17f6503e4c5a3a269ecf93d6c92d" }, "user_id": "acaacc940c9ebfe798dee68acf5c", "zipcode": "" }, { "name": "df ", "token": null, "user_id": "e0efe9810ca289ccd590bce48051", "zipcode": "" }, { "name": "Io", "phone": "88888888", "state": "NY", "token": null, "user_id": "c88ce38d0c86f786c3a4b0f9f967", "zipcode": "13201" } ] const resFilter = data.filter(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d"); console.log(resFilter); const resObj = data.find(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d"); console.log(resObj);

You must use the following code const finded = data.filter(user => user?.token?.token ==="value"}) console.log(finded);您必须使用以下代码 const finded = data.filter(user => user?.token?.token ==="value"}) console.log(finded);

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

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