Friday, 29 September 2023

To search for an element in a JavaScript array based on a username

To search for an element in a JavaScript array based on a username, you can use the `Array.prototype.find()` method. This method will iterate through the array and return the first element that matches the provided condition. Here's how you can do it:

Suppose you have an array of user objects like this:

```javascript
const users = [
  { username: "user1", name: "John" },
  { username: "user2", name: "Jane" },
  { username: "user3", name: "Bob" },
  // ... other user objects
];
```

You can search for a user by their username using `Array.prototype.find()` like this:

```javascript
const usernameToSearch = "user2"; // Change this to the username you want to search for

const foundUser = users.find(user => user.username === usernameToSearch);

if (foundUser) {
  console.log("User found:", foundUser.name);
} else {
  console.log("User not found");
}
```

In this example, `Array.prototype.find()` iterates through the `users` array and checks if the `username` property of each user object matches the `usernameToSearch` value. If a match is found, `foundUser` will hold the user object with the matching username. If no match is found, `foundUser` will be `undefined`.

Adjust `usernameToSearch` to the username you want to search for, and the code will find the corresponding user object or indicate if the user is not found.

*************************************************************************

To search for the object in your JSON data based on the `trashed_user.name` property in JavaScript, you can use the `Array.prototype.find()` method just like in the previous example. However, since your data appears to be a single object rather than an array, you don't need to iterate over an array. Instead, you can directly access the `trashed_user.name` property. Here's how you can do it:

```javascript
const jsonData = {
  "id": 1  "created_at": "2023-07-17T09:38:10.000000Z",
  "trashed_user": {
    "id": 1,
    "name": "Jayesh Patel",
  }
};

const nameToSearch = "Jayesh Patel"; // Change this to the name you want to search for

if (jsonData.trashed_user.name === nameToSearch) {
  console.log("Object found:", jsonData);
} else {
  console.log("Object not found");
}
```

In this code, we directly access the `trashed_user.name` property of the `jsonData` object and compare it to the `nameToSearch`. If there is a match, it will log the entire object. If there is no match, it will indicate that the object was not found. Adjust `nameToSearch` to the name you want to search for.


*************************************************************************

If you want to search for an object in an array case-insensitively (meaning it should match both small and capital letters), you can convert both the search string and the data to a consistent case (e.g., lowercase) before performing the search. Here's how you can do that:

```javascript
const jsonData = {
  "id": 1  "created_at": "2023-07-17T09:38:10.000000Z",
  "trashed_user": {
    "id": 1,
    "name": "Jayesh Patel",
  }
};

const nameToSearch = "Jayesh patel"; // Change this to the name you want to search for

const foundObject = jsonArray.find(item => item.trashed_user.name.toLowerCase() === nameToSearch.toLowerCase());

if (foundObject) {
  console.log("Object found:", foundObject);
} else {
  console.log("Object not found");
}
```

In this code, both the `nameToSearch` and the `trashed_user.name` properties are converted to lowercase using `.toLowerCase()` before comparison. This allows for a case-insensitive search, so it will match regardless of the letter casing in the search string and the data. 

************************************************************************


If you want to perform a "like" search, meaning you want to find objects in the array where the `trashed_user.name` property contains a specific substring, you can use the `Array.prototype.filter()` method to filter the array based on a custom condition. Here's how you can do it:

```javascript
const jsonArray = [
  {
    "id": 1,
    "created_at": "2023-07-17T09:38:10.000000Z",
    "trashed_user": {
      "id": 1,
      "name": "Admin Testing",
      "user_role": 0
    }
  },
  // ... other objects in the array
];

const searchTerm = "Testing"; // Change this to the substring you want to search for

const filteredObjects = jsonArray.filter(item => item.trashed_user.name.toLowerCase().includes(searchTerm.toLowerCase()));

if (filteredObjects.length > 0) {
  console.log("Matching objects found:", filteredObjects);
} else {
  console.log("No matching objects found");
}
```

In this code, we use the `Array.prototype.filter()` method to filter the `jsonArray` based on whether the `trashed_user.name` property contains the specified `searchTerm`. Both the `trashed_user.name` and `searchTerm` are converted to lowercase using `.toLowerCase()` for a case-insensitive search. The `filteredObjects` array will contain all objects that match the search criteria, and you can access and manipulate them as needed.

*********************************************************************


If you want to search for all records in an array that are related to "ankita," not just a single record, you can modify the code to use the `Array.prototype.filter()` method to filter multiple matching records. Here's how you can do it:

```javascript
const jsonArray = [
  {
    "id": 1,
    "created_at": "2023-07-17T09:38:10.000000Z",
    "trashed_user": {
      "id": 2,
      "name": "Rakesh Patel",
      "user_role": 0
    }
  },
  {
    "id": 2,
    "created_at": "2023-07-17T09:38:10.000000Z",
    "trashed_user": {
      "id": 265,
      "name": "Ramesh Patel",
        "user_role": 0
    }
  },
  // ... other objects in the array
];

const searchTerm = "Patel"; // Change this to the substring you want to search for

const filteredObjects = jsonArray.filter(item => item.trashed_user.name.toLowerCase().includes(searchTerm.toLowerCase()));

if (filteredObjects.length > 0) {
  console.log("Matching objects found:", filteredObjects);
} else {
  console.log("No matching objects found");
}
```

This code will filter all records in the `jsonArray` where the `trashed_user.name` property contains the specified `searchTerm`. It stores all matching records in the `filteredObjects` array, and you can access and manipulate them as needed.

Monday, 25 September 2023

How to Use HTML5 File Drag and Drop

HTML Drag and Drop interfaces enable web applications to drag and drop files on a web page. This document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page.

Why Need Drag and Drop File Upload Feature?
We always want to have a better user experience on the website. Giving the drag and drop file uploader is convenient for users. A lot of popular websites like Facebook and WordPress are already using this technique.

This feature looks better compared to the traditional way of file uploading. It also improves the user experience as the user simply drags the file and it gets uploaded asynchronously.

Our file uploader will have both options. One can upload the file either using drag and drop or through the file input.

    
 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Drag-and-Drop Media Upload</title>
        <style>
            /* Style the drop zone */
            #file-drop-zone {
                width: 300px;
                height: 150px;
                border: 2px dashed #ccc;
                text-align: center;
                padding: 20px;
                margin: 20px auto;
            }
        </style>
    </head>
    <body>
        <div id="file-drop-zone" ondrop="drop(event)" ondragover="allowDrop(event)">
            Drop media files here.
        </div>

        <script>
            function allowDrop(event) {
                event.preventDefault();
                // Add a visual indication that it's a valid drop target (e.g., change border color)
                event.target.style.border = '2px dashed #007bff';
            }

            function drop(event) {
                event.preventDefault();
                event.target.style.border = '2px dashed #ccc'; // Reset the border color

                const files = event.dataTransfer.files;
                const fileDisplay = document.createElement('ul');

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const listItem = document.createElement('li');
                    listItem.textContent = `${file.name} (${formatBytes(file.size)})`;
                    fileDisplay.appendChild(listItem);
                }

                document.body.appendChild(fileDisplay);
            }

            // Function to format file size in a human-readable format
            function formatBytes(bytes, decimals = 2) {
                if (bytes === 0) return '0 Bytes';

                const k = 1024;
                const dm = decimals < 0 ? 0 : decimals;
                const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

                const i = Math.floor(Math.log(bytes) / Math.log(k));

                return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
            }
        </script>
    </body>
    </html>
 

        In this code:

  1. The HTML file contains a file-drop-zone div element where you can drag and drop files.
  2. The allowDrop function is called when a file is dragged over the drop zone, preventing the default behavior and adding a visual indication that it's a valid drop target.
  3. The drop function handles the dropped files. It displays the names and sizes of the dropped files in an unordered list.
  4. There's also a formatBytes function to format file sizes in a human-readable format.
  5. Remember that this is a simple example. In a real application, you would typically send the uploaded files to a server for storage and implement error handling and security measures.


Node.js Basic to Advance

Node.js Basic to Advance Blog Node.js Tutorial: From Basic to Advance Everything you need to become a...