add the value to the array only if it is enclosed in quotation marks

Input array

var array = [
  'name',
  '"Mobile Number"',
  '"mobile1,mobile2"',
  'email2',
  'Address',
  'email21'
]

var matchkey = 'mobile1,mobile2'

res = res.map(function (value) {
if(value==matchkey){
return value+".string()"
}
else {
return value+".auto()"
}
            
        })

Current Output from above code

[
  'name.auto()',
  '"Mobile Number".auto()',
  '"mobile1,mobile2".auto()',
  'email2.auto()',
  'Address.auto()',
  'email21.auto()'
]

Expected Ouptput;

[
  'name',
  '"Mobile Number.auto()"',
  '"mobile1,mobile2.string()"',
  'email2.auto()',
  'Address.auto()',
  'email21.auto()'
]

Note: I don't wish to eliminate double quotes inside single quotes as they are necessary for future processing

Answer №1

The matchkey you provided is not found in the array.

String stored in array: '"mobile1,mobile2"'

MatchKey found: 'mobile1,mobile2'

To proceed, update your matchkey to:

var matchkey = '"mobile1,mobile2"'

It seems that your intended output is to have the name string without any function access. In that case, consider adding an else if statement as shown below:

if(value == matchkey){
    return value+".string()";
} else if(value == 'name') {
    return value;
} else {
    return value+".auto()";
}

Answer №2

Could it be this solution?

let data = [
  'name',
  '"Mobile Number"',
  '"mobile1,mobile2"',
  'email2',
  'Address',
  'email21'
]

let searchKey = '"mobile1,mobile2"'

const result = data.map(function(item) {
  return item == searchKey ? item.slice(0, -1) + ".string()\"" : 
    item.endsWith('"') ? item.slice(0, -1) + ".auto()" + '"' : item + ".auto()"
})
console.log(result)

Answer №3

To perform the substitution, you can utilize regular expressions (regex):

const output = elements.map((item) =>
  item.replace(/^("?)(.*?)("?)$/, function () {
    return `${
      arguments[1]
    }${arguments[2] + (arguments[2] === comparisonKey ? '.modify()' : '.alter()')}${arguments[3]}`;
  })
);

Answer №4

If you make the switch from value==matchkey to value.includes(matchkey), you should see the desired result.

var items = [
  "username",
  '"Phone Number"',
  '"phone1,phone2"',
  "email3",
  "Location",
  "email31",
];

var matchkey = "phone1,phone2";

result = items.map(function (value) {
  if (value.includes(matchkey)) {
    return value + ".string()";
  } else {
    return value + ".auto()";
  }
});

console.log(result);

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

Issue concerning the oj-button element in Oracle JET framework

What causes the oj-button to continually concatenate its label text when clicked repeatedly? For an example of this behavior, refer to the button in the following cookbook: Is it normal for the label text to keep multiplying with each click, resulting in ...

Understanding the concept of state management in React is essential for developers

Suppose my web page contains two components and each has its own unique state. If I modify the state of one component, will it also impact the second component? ...

In Typescript, every expression inherently holds a value

I have a specific interface set up as shown below: interface Actions { run: any; execute: any; } const actions: Actions = { run: require("./runAction"), execute: require("./executeAction"), } My goal is to call the functions a ...

Learn how to dynamically change the state of a button by using the *ngIf directive

For the code snippet below, my objective is as follows: If the index equals 0, then the button's text should be "info" and it should be enabled. Also, If the index equals 1, then the button's text should be "INFO" and it should be disabled. Ple ...

I am experiencing an issue with my Angular directive where the button click does not

Check out this page for guidance on adding a div with a button click in AngularJS: How to add div with a button click in angularJs I attempted to create an angular directive that should add a div to my HTML page when a button is clicked. However, upon cli ...

When checking the angular-cli.json file, it reported the error "moment is not defined."

I'm having some challenges with Angular2 development using angular-cli. One thing I'm unsure about is how to include external CSS and JavaScript libraries in my project. Below is my angular-cli configuration where I have loaded numerous librari ...

Is it necessary to establish a connection to my mongodb database directly within my jest test file, or is it permissible to invoke functions from separate classes that handle the database connection?

Currently in the process of testing my database functions using jest. My javascript file contains a variety of functions that connect to the database, retrieve data, and return an array. The issue I'm facing is when calling these functions from my jes ...

Encountering an undefined i18next error

When trying to initialize i18next, I encountered the following error message: Uncaught TypeError: Cannot read property 'use' of undefined Here is the code snippet that is causing the issue: import i18n from 'i18next';// Getting eslin ...

Nodejs and Express are seamlessly integrating error handling with database submission, ensuring a smooth flow of data processing

While testing my backend using nodejs and express, I encountered an issue with error handling in postman. The error message displays correctly for the 'Multiplier' column validation, but despite this, the data is being submitted into my mysql wor ...

Contingent upon the prop in Vue 2, determine whether to render the slot with a wrapper or

My component is simple - it just adds styling to a slot. The styling part is straightforward: it adds padding, margin, border, and background color based on the props passed. Right now, there is a wrapper component with a default slot inside. We bind class ...

Unable to transform SVG files in Next.js Jest version 28

Currently, my setup involves Next.js version 12.0.7, Jest version 28.1.0, and the use of the next-react-svg library for importing SVG files into components. The configuration in my jest.config.js file looks like this: // jest.config.js const nextJest = re ...

Sending data to a child component through an onClick event handler

Can someone help me figure out how to make the Overlay inside the InviteButton visible when clicking on it? I want to use the prop show={true}, but I'm struggling with this implementation. Any assistance or guidance would be greatly appreciated. ----f ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

Add jQuery to a JavaScript document

Apologies for any language barriers, English is not my first language... I currently have a my_js.js file that is included in all my asp pages. However, I now need to incorporate jQuery into this specific page without directly adding script tags like < ...

How can I utilize JQ to display two specific objects located within an array in a JSON file?

My Json file begins with two objects containing description and rtmp_url details. I am striving to extract only these two fields. { "features": [ { "type": "Feature", "geometry": ...

Troubleshooting Google Chrome Extension: chrome.storage.sync.get malfunctioning

Could anyone help me troubleshoot my code issue? I successfully save the data, but when trying to load it, the saved data cannot be found: Here is the code snippet: $('#SaveSet').click(function() { var theValue = $('#col').val(); ...

array_search does not return any results

I am facing an issue with the following array: <?php $a = array( "apple"=>"uniqid1", "apple"=>"uniqid2", "apple"=>"uniqid3", "bannana"=>"uniqid4" ...

How can I position a div in the center of a fullpage.js slide?

I'm currently utilizing the fullPage.js plugin sourced from this link: . I have successfully implemented vertical slides by using the following HTML code: <div class="section" id="section2"> <div class="slide" id="slide1"> ...

What is the process for adding my JSON data to a select dropdown list?

Looking to populate a selectlist in HTML with options retrieved from an API. Below is the HTML code : <div id="example" role="application"> <div class="demo-section k-header"> <select id="FeaturesSelec ...