In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true.

const Ids = ['743156', '743157']
[
    {
        "id": "743156",
        "role": "Authorized Redistributor (AR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743157",
        "role": "System Of Record (SOR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743158",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743159",
        "role": "System Of Record (SOR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743976",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
]

As the user interacts with the checkboxes and updates them, they have the ability to change the checked value, potentially affecting other objects. My goal is to identify which objects have their checked property set to true, excluding the initial two objects that were checked.

If there are no new checkboxes checked by the user, I expect an empty object {}. I do not want the initially checked checkboxes with ids 743156 & 743157 to be included in the result.

 {
        "id": "743157",
        "role": "System Of Record (SOR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743158",
        "role": "Authorized Redistributor (AR)",
        "checked": true,
        "checkBoxPatched": true
    }

Answer №1

Using the same_ids_lists function, we can determine if there have been any modifications in the selection of items. It might not always be essential to arrange and duplicate the list arrays if their order remains consistent.

const ids = ['743156', '743157'];
const data = [
    {
        "id": "743156",
        "role": "Authorized Redistributor (AR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743157",
        "role": "System Of Record (SOR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743158",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743159",
        "role": "System Of Record (SOR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743976",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
];

const same_ids_lists = (list_1, list_2) =>
  [...list_1].sort().join('-') === [...list_2].sort().join('-');

const get_updated_checked_items = (data, previous_ids) => {
  const checkedItems = data.filter( (item) => item.checked );
  
  const is_changed = same_ids_lists(
    checkedItems.map( (item) => item.id ),
    previous_ids
  );
  
  return is_changed ? false : checkedItems;
};

console.log('No changes: ', get_updated_checked_items(data, ids));

data[0].checked = false;
data[2].checked = true;

console.log('Changes made: ', get_updated_checked_items(data, ids));

Edit: Revised get_updated_checked_items to return false for unchanged scenarios as distinguishing between unchanged and without checked items would be impossible otherwise.

Answer №2

If you want to exclude the first two items from the ids array and retrieve the checked values,

const data = [
    {
        "id": "743156",
        "role": "Authorized Redistributor (AR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743157",
        "role": "System Of Record (SOR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743158",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743159",
        "role": "System Of Record (SOR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743976",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    }
];

const ids = ["743156", "743157"];
const checkedArr = [];
data.map((d) => {
    if (!ids.includes(d.id) && d.checked === true) {
        checkedArr.push(d);
    }
})

console.log(checkedArr);

Answer №3

To filter data in JavaScript, you can use the filter() method.

const arrObj = [
    {
        "id": "743156",
        "role": "Authorized Redistributor (AR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743157",
        "role": "System Of Record (SOR)",
        "checked": true,
        "checkBoxPatched": true
    },
    {
        "id": "743158",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743159",
        "role": "System Of Record (SOR)",
        "checked": false,
        "checkBoxPatched": true
    },
    {
        "id": "743976",
        "role": "Authorized Redistributor (AR)",
        "checked": false,
        "checkBoxPatched": true
    },
]

const filteredData = arrObj.filter((_obj)=> _obj.checked === true);

console.log(filteredData)

More information on Array.prototype.filter()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Version 2: "In case of an empty input field, the submit button should be

After experimenting with two different codes on my websites, I encountered an issue. The first code looked like this: $(document).ready(function(){ $('.sendButton').attr('disabled', true); $('#message').keyup(function ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

NodeJS buffer is not capable of handling incomplete TCP stream data

While troubleshooting my TCP JSON stream on the live server, I discovered that if the data streamed to me in JSON format is excessive, it doesn't consistently parse correctly. It requires multiple streams for successful parsing. Here is the code I am ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

Navigating through and extracting data from an object in JavaScript

Given the function call destroyer([1, 2, 3, 1, 2, 3], 2, 3);, I am trying to retrieve the last 2, 3 part after the initial array. However, I am unsure about how to achieve this. When I use return arr[6]; or return arr[1][0], both statements do not return ...

Removing an item from an array containing several objects

I have an array that looks like this: var participants = [ {username: "john", time: null}, {username: "samira", time: null}, {username: "mike", time: null}, {username: "son", time:null} ] To remove an item based on the username, I can do the f ...

Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

Failure to set X-XSRF-TOKEN header in Angular5

After exploring several solutions, I have yet to find one that works for me. This issue on Github closely mirrors my problem (https://github.com/angular/angular/issues/20511) My setup includes Angular 5.2.5, Chrome Version 65.0.3325.146, and Spring Boot ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...

Using a forward slash '/' to navigate to a specific URL

When routing to a page, I encounter an issue with sending IDs that may contain slashes '/'. This poses a problem because the route will change as a result. For example: somepage/my-id/2f On the destination page, I need to be able to interpret t ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

Utilizing ES6 promises in node.js to send a null response

I'm looking for assistance on how to execute a query using ES6 native promises in node.js. The code I have below is what I've been working with: let arr= []; conn.query('select * from table1', (err, b) => { for (let i = 0; i ...

What is the best way to determine the appropriate generic type for this situation?

Here is an example of some code: type secondaryObjectConstraint = { [key: string]: number } abstract class Base<TObject extends object, TSecondaryObject extends secondaryObjectConstraint> {} type secondaryObjectType = { myProp: number } c ...

Verify the legitimacy of the object

I'm encountering an issue while attempting to create a function that verifies the validity of an object. const isPeriodValid = (period: Period | null): boolean => { return period && period.start && period.end; } export interfac ...

There seems to be an issue with the import class for React PropTypes. The prop

I have multiple oversized items that are utilized in numerous components, so I created a PropTypes file for each item. For example: PropTypes/PropLargeObject.js This file contains: import PropTypes from "prop-types"; const PropLargeObject = Prop ...

Adjust the background of the page at regular intervals

I currently have: <script type='text/javascript'> var imageID=0; function changeimage(every_seconds){ //change the image if(!imageID){ document.getByTagName("body").src="icwXI.jpg"; imageID++; } else{if(imageID==1){ document.ge ...