检查数组是否包含属性并将其绑定到新数组

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

我有一个绑定的数组,如下所示:

const newdata = json.map((c) => {
   return {
     "User Name": c.userName,
     Email: c.email,
     Groups: c.newArrGroups.map(a => a.name).toString(),
     Version: c.clientVersion
   };
});

上面的

json
数据是从函数传递的,现在我需要检查数组是否具有特定属性。所以我找到了一个可以检查属性的东西,如下:

json.hasOwnProperty("userName")

我现在有两件事需要验证。 One - 必须检查特定属性是否在数组中,如果该属性不存在,则从那里删除它; 第二 - 数组对象内可能有数组。以上是否有任何解决方案,我可以检查如下:

const newdata = json.map((c) => {
  return {

    if(json.hasOwnProperty("userName")) {
      "User Name": c.userName, //To check if property exists, then bind it here
    }

    Email: c.email,

    if(json.newArrGroups.hasOwnProperty("name")) {
      Groups: c.newArrGroups.map(a => a.name).toString(), //This checking is required as well as there would be arrays inside an array object
    }
    
    Version: c.clientVersion
  };
});
arrays angular typescript angular15
1个回答
0
投票

这只是一个基本问题。我已经演示了它(在这里)[https://onecompiler.com/html/4335ayxfa]。

// Sample JSON data
const json = [
    {
        userName: "JohnDoe",
        email: "[email protected]",
        newArrGroups: [{ name: "Admin" }, { name: "User" }],
        clientVersion: "1.0.0"
    },
    {
        email: "[email protected]",
        newArrGroups: [{ name: "User" }],
        clientVersion: "1.0.1"
    },
    {
        userName: "Alice",
        newArrGroups: [{ name: "Admin" }],
        clientVersion: "1.0.2"
    }
];

// Mapping function
const newdata = json.map((c) => {
    const result = {};
    if (c.hasOwnProperty("userName")) {
        result["User Name"] = c.userName;
    }

    if (c.hasOwnProperty("email")) {
        result.Email = c.email;
    }

    if (c.hasOwnProperty("newArrGroups") && Array.isArray(c.newArrGroups)) {
        result.Groups = c.newArrGroups.map(a => a.name).toString();
    }

    if (c.hasOwnProperty("clientVersion")) {
        result.Version = c.clientVersion;
    }

    return result;
});

// Display the result on the web page
document.getElementById('output').textContent = JSON.stringify(newdata, null, 2);
<h1>Mapped Data</h1>
<div id="output"></div>

请尝试一下,如果有帮助请告诉我! :)

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