Search code examples
arraysangulartypescriptangular15

Check Array Contains A Property and Bind It To A New Array


I've an array that I am binding as follows:

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

The above json data is passed from a function, now I've a requirement to check if the array has specific properties. So I found something that can check the properties as follows:

json.hasOwnProperty("userName")

I've two things to verify now. One - Have to check if specific property is in the array and if the property doesn't exist, then remove it from there; Second - There could be arrays inside an array object. Is there any solution with the above that I can check something as follows:

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
  };
});

Solution

  • just a basic problem here. I have demonstrated it here.

    // Sample JSON data
    const json = [
        {
            userName: "JohnDoe",
            email: "john.doe@example.com",
            newArrGroups: [{ name: "Admin" }, { name: "User" }],
            clientVersion: "1.0.0"
        },
        {
            email: "jane.doe@example.com",
            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>

    Please try it and let me know if it helps! :)