尝试检查对象数组中的对象数组中是否存在键

问题描述 投票:0回答:1

如果在changeFields数组中“printLogs”键是否存在,我需要一种方法来返回true或false。该对象如下所示。我尝试过循环,但不知何故无法让我的头环绕它。

const printObj = [
  {
    _id: "656a69e14",
    document: { _id: "65b891" },
    user: "654cfbba3ea455b55b057195",
    changeFields: [
      {
        change: "update",
        quantity: [
          2,
          3,
          "2023 1 Oz Silver Maple Leaf Coin - Royal Canadian Mint",
        ],
      },
      { change: "update", subTotal: ["77.88", "116.82"] },
      { change: "update", totalAmount: ["107.88", "146.82"] },
    ],
    createdAt: "2023-12-01T19:10:54.575Z",
    updatedAt: "2023-12-01T19:10:54.575Z",
    __v: 0,
  },
  {
    _id: "65e0e",
    document: { _id: "651" },
    user: "",
    changeFields: [{ printLogs: "An order has been printed" }],
    createdAt: "",
    updatedAt: "",
    __v: 0,
  },
{},

]

我在内置函数中尝试过 javascript。下面的代码在某种程度上有效,但如果 printLogs 存在于 changeFields 中,我需要返回 true 或 false。

const value = printObj.filter(function (x) {
  x.changeFields.filter(function (o) {
    console.log(o, o.hasOwnProperty("printLogs"));
  });
});
javascript arrays loops object key-value
1个回答
0
投票

我在下面添加代码。

const printObj = [
  {
    _id: "656a69e14",
    document: { _id: "65b891" },
    user: "654cfbba3ea455b55b057195",
    changeFields: [
      {
        change: "update",
        quantity: [
          2,
          3,
          "2023 1 Oz Silver Maple Leaf Coin - Royal Canadian Mint",
        ],
      },
      { change: "update", subTotal: ["77.88", "116.82"] },
      { change: "update", totalAmount: ["107.88", "146.82"] },
    ],
    createdAt: "2023-12-01T19:10:54.575Z",
    updatedAt: "2023-12-01T19:10:54.575Z",
    __v: 0,
  },
  {
    _id: "65e0e",
    document: { _id: "651" },
    user: "",
    changeFields: [{ printLogs: "An order has been printed" }],
    createdAt: "",
    updatedAt: "",
    __v: 0,
  },
  {},
];

const result = printObj.map(
  (obj) =>
    !!obj.changeFields?.filter(
      (item) => Object.keys(item).indexOf("printLogs") !== -1
    ).length
);

console.log(result);

© www.soinside.com 2019 - 2024. All rights reserved.