Disabling `no-dupe-keys` in ESLint does not seem to be effective

Currently, I am working on a project where I have incorporated Typescript and ESLint. However, I have encountered an issue with the error message stating:

An object literal cannot have multiple properties with the same name.

I am looking to disable this specific checking for this error in the line, but I am unsure of how to go about it.

This seems related to the no-dupe-keys rule mentioned in the documentation, yet it does not seem to function properly within my project context.

testFetch.ts

import fetch from 'node-fetch';

export function testRequest() {
  const url:string = 'https://example.com/api';
  
  // eslint-disable-next-line camelcase
  const test_camel = 'sd'

  const body = {
    "key[0]": "arr_val_1",
    // eslint-disable-next-line no-dupe-keys
    "key[0]": "arr_val_2",
    // eslint-disable-next-line camelcase
    "key[1]": test_camel,
  }

  fetch(url, {body})
  .then((res) => res.json())
  .then((res) => console.log(res))
  .catch((err) => console.error('error:' + err));
}

I understand that such unconventional body parameters are necessary here.

Despite this, as depicted in the screenshot, the linter still highlights the issue.

https://i.stack.imgur.com/0B4Zr.png

.eslitrc.cjs

/* eslint-env node */
module.exports = {
  extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  root: true,
  rules: {
    "no-dupe-keys": "error",
    camelcase: "error",
  },
  ignorePatterns: [ 
        "test/*", 
        "dist/*",
        ".eslintrc.cjs"
    ],
  // "noInlineConfig": true,
};

While the code functions perfectly fine in the playground, it fails to do so in the actual project:

https://i.stack.imgur.com/SRzIB.png

Answer №1

In the realm of javascript, it is absolutely improbable to possess an object with two identical keys. Therefore, no option in eslint or typescript will allow you to achieve this.

It seems like the API necessitates a form-data structure.

An illustrative example can be found at https://www.npmjs.com/package/node-fetch#formdata

import fetch, { FormData } from 'node-fetch'

const httpbin = 'https://httpbin.org/post'
const formData = new FormData()

formData.append('key[0]', 'Hello, world!')
formData.append('key[0]', 'new name.txt')

const response = await fetch(httpbin, { method: 'POST', body: formData })
const data = await response.json()

console.log(data)

Answer №2

When working with JSON, it's important to ensure that keys are unique and not repeated within the same object. This prevents any confusion or conflicts when parsing the data. If you need to send multiple values for a particular key (such as key[0]) as query parameters to a backend system, one approach is to use an array structure in the request.

import fetch from 'node-fetch';

export function sendRequest() {
  const url:string = 'https://example.com/api';
  
  // eslint-disable-next-line camelcase
  const test_camel = 'sd'

  const requestBody = {
    "key[0]": ["arr_val_1","arr_val_2"],
    // eslint-disable-next-line camelcase
    "key[1]": test_camel,
  }

  fetch(url, {method: 'POST', body: JSON.stringify(requestBody)})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:' + error));
}

Answer №3

Upon analyzing the image provided, it is clear that the error message makes reference to ts1117. This serves as an indication that the error stems from TypeScript rather than eslint. To resolve this issue, you can overcome the error by disabling TypeScript for the specific line in question with the following adjustments.

  const body = {
    "key[0]": "arr_val_1",
    //@ts-ignore
    "key[0]": "arr_val_2",
    // eslint-disable-next-line camelcase
    "key[1]": test_camel,
  }

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 are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

Combine Vue Plugin Styles without Using Components

Question Time To clarify, when I mention 'without component', I am referring to my plugin being a custom Vue Directive that does not rely on a template. It acts as a wrapper for a class, without the need for an additional component. However, I a ...

Errors and disruptions caused by SmoothScroll, ScrollMagic, and GSAP triggering glitches, jumps, and crashes

Connecting ScrollMagic with GSAP is not an issue - it works seamlessly. However, I encountered a problem when trying to implement smooth scrolling for my mouse. I added a smooth scrolling plugin to my project from this link: http://www.jqueryscript.net/ani ...

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Could not locate the provider: $stateProvider

It's puzzling to me why this code is not recognizing the $stateProvider. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $stateProvider This is a simple example of a module: ( ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Using conditional rendering to set an icon in a ChipField component in React Admin

One feature in my React Admin App is a Datagrid with a ChipField displaying a text property. I want to enhance this by adding an icon to the ChipField using the icon prop, which should change based on the text value. This is my current approach: expor ...

Removing an item from an ng-repeat loop while also dealing with a FormController within

I am encountering a significant issue with form inputs nested within the ng-repeat directive. I require an input that is an array and can vary in size; allowing users to add or remove parts of the form. Within the ng-repeat directive, there is an ng-form ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

Issues with the execution of Jquery function

Hey guys, take a look at my code: //Additional Jquery codes // display_popup_crop : revealing the crop popup function display_popup_crop(link) { alert("show_popup_crop function is triggered!"); // changing the photo source $('#cropbox&a ...

Encountering problems with parsing a lengthy JSON file

Can you spot the issue here? let stringinsta = JSON.parse({ "access_token":"129261**5ea59a4da481c65", "user":{ "username":"carlos_bellesso", ...

Employ CSS flexbox and/or JavaScript for creating a customizable webpage

I am in the process of developing a basic IDE for an educational programming language that has similarities to Karel the Dog. One major issue I am encountering is creating the foundation HTML page. The IDE consists of 4 main areas: Toolbox (contains but ...

Using AngularJS to send a model to ui-select

Here is the scenario at hand: A form includes a directive known as <timeZone ng-model="formModel.timeZone" This directive communicates with a web service to fetch timezone information The directive then presents the timezones in a ui-select dropdown ...

Querying a list of objects with nested pointers using the Parse.com Javascript API

How can I efficiently query my Parse.com backend for a list of objects that contain specific pointers within them? For example, if ObjectA contains a list of pointers to ObjectB, how can I query for all ObjectA's that have ObjectB in their list? I a ...

Click and release file upload

I am working on creating a drag and drop upload feature where the user can drop files onto a div, and then click an upload button to send them to the server. I'm facing an issue with JavaScript not recognizing the variable fd. How can I pass that vari ...

Automate your functions using Javascript!

Hello, I have written a code snippet that triggers an action on mouse click. Initially, I created a function that scrolls the screen to a specific element upon clicking another element: (function($) { $.fn.goTo = function() { $('html, bo ...

Tips for transitioning frontend JS to Angular 2 for seamless integration with a PHP MVC backend system

I currently have a robust PHP MVC web application that utilizes jQuery for click events and modal dialog rendering. To align with up-to-date frontend technologies, I am looking to revamp the JavaScript code to function within Angular 2. However, I am faced ...

Utilize the input type=date value in the date function to obtain a specific format

How can I pass the value of input type=date to a JavaScript date function? In my HTML code, I have used: <input type=date ng-model="dueDate"> <input type="time" ng-model="dueTime"> <button class="button button-block" ng-click="upload_dueda ...

Sending a JavaScript Array to PHP results in receiving Undefined or Disallowed Key Characters

I've been grappling with this problem for a few days now. I have an array in JavaScript that I need to send over to my PHP method. This is my PHP code: public function saveCampaignSendToMediaOwner() { $result = $this->input->post(); e ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...