Update the array by incorporating a new object that corresponds to a provided list with a unique key-value pair

When selecting objects from a list using a checkbox, I want to make the selection recognizable by adding a new key-value pair to the selected objects with the label of the selected value.

This is what I have tried:

var checkCheckboxOnOff = [{"fieldName":"Category","picklistValue":"Technology"},{"fieldName":"Region","picklistValue":"Central"}]

Here is how I loop through checkCheckboxOnOff to select objects from a list:

filteredList = serverList.filter(function(item) { return item[checkCheckboxOnOff[i].fieldName] == checkCheckboxOnOff[i].picklistValue});

While looping through the list, I add a key and value to the selected objects and push them into a filter array:

    filteredList.forEach(function(n) {n.arrayPicklist = checkCheckboxOnOff.fieldName});
 Array.prototype.push.apply(filterArray,filteredList[i]); 

The issue I am facing is that when I select an object twice, both selected objects end up being updated with the last key and value. I expect each selected object to have a unique value even if selected multiple times.

For example:

[{"Id":"120"},{"Id":"121"}]

2nd Selection

[{"Id":"123"},{"Id":"121"}]

Expected outcome:

[{"Id":"120","arrayPicklist":"Category"},
{"Id":"121","arrayPicklist":"Category"},{"Id":"123","arrayPicklist":"Region"},
{"Id":"121","arrayPicklist":"Region"}]

Current result

[{"Id":"120","arrayPicklist":"Category"},
    {"Id":"121","arrayPicklist":"Region"},{"Id":"123","arrayPicklist":"Region"},
    {"Id":"121","arrayPicklist":"Region"}]

There seems to be an issue with getting undefined for the value, please refer to this fiddle: https://jsfiddle.net/Lcg1qca3/18/

Answer №1

The issue lies within

n.arrayPicklist = checkCheckboxOnOff.fieldName

Instead of trying to access a fieldName property on an array, you should be referencing an index in the checkCheckboxOnOff array.

To fix this problem, replace that line with:

opleidingfilter.forEach(function(n,i) {n.arrayPicklist = checkCheckboxOnOff[i].fieldName});

By doing this, you will have access to the index property in your iterator and be able to retrieve each item in your checkCheckboxOnOff array.

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

What is the best way to implement auto-refreshing with reactQuery?

Hey there! I'm currently working with a GraphQL API and I'm trying to automatically refetch data at regular intervals (e.g. every 3 seconds). I've been using React Query and have tried some workarounds like using setInterval, but it's n ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...

The Gridsome website deployed on Netlify seems to be experiencing some issues. When clicking on links, the pages are not loading properly despite

After deploying my site on Netlify, I encountered an issue where the URL updates when clicking on links on the landing page, but the content does not show unless the page is refreshed. Interestingly, this issue does not occur on my local development server ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...

Instructions on how to insert information into an array by clicking a button

As a newbie JavaScript programmer, I am struggling to figure out how to make my code work as a function. I want to update the ajax_data array every time I click the add row button. Fresh JS coder looking for some guidance. var ajax_data = [{ Type: "A ...

Guide to traversing a JSON Array using PHP and showcasing it in an HTML Table

I'm struggling to parse a JSON Array Response in PHP and display the values in an HTML Table. I have limited experience with PHP-JSON and need some guidance on how to achieve this. $curl_response = curl_exec($curl); echo $curl_response . PHP_EOL; JSO ...

Using selenium to extract data from websites featuring javascript elements

As a beginner in the world of web scraping and using Selenium, I am facing a challenge with a page that requires a JavaScript script on a button to navigate to the next page. I came across a snippet of code (Click a Button in Scrapy) on Stack Overflow, but ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

Retrieve a selection of data from the data.json file and mix it up

My webpage has a json data sheet containing multiple objects that I am currently showcasing. { "objects": [ ... ] } In terms of templating: $(function () { $.getJSON('data.json', function(data) { var template = $('#objectstpl') ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

The parcel command seems to be inactive and is not registered as a valid command

After successfully installing Parcel using npm, I created a package.json file with the following content: { "name": "example", "version": "0.1.0", "source": "src/index.js", "m ...

utilize javascript variables within an HTML document

I keep encountering a strange error (Express 400 Error: Bad Request) Some lines are translated to the variable value, while others just output an error. This is an example of my code: exports.add_comment = function(req, res){ var id = req.params.id; ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

Unable to insert hyperlinks into table rows within a React application

A React function was created by me to display a table. This is how the table appears. It accepts JSON as a parameter: { "id": 1, "firstName": "Richard", "lastName": "Morrison", "number ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

The br tag in HTML cannot be utilized in conjunction with JavaScript

I am currently working on a project involving HTML and JavaScript. I have a "textarea" where data is inserted into the database upon pressing the "Enter key." However, I am encountering two issues: Currently unable to save data like "Lorem Ipsum" (the ...