Include parameters in the function so that it will only run if the value matches a name in the provided

Let's start with an object:

const oData = { 
  name: 'Dragon', 
  weapon: 'fire-breath', 
  likes: 'Gold, Flying, Power', 
  dislikes: 'Ice, Humans, Knights'
};

This object is then passed to the following function:

fConvertValuesToArrays(obj) {
    for (const i in obj) { 
      obj[i] = Array.isArray(obj[i]) ? obj[i] : [obj[i]]; 
    }
    return obj;
  },

The above function successfully transforms all the values into arrays. Now, I have a requirement where this transformation should only occur if the value matches any of the items in this array:

const aNamesToMatch = [ 'likes', 'dislikes' ];

Is there a way to incorporate this check within the existing function or should I create a separate one and call it from fConvertValuesToArrays? If so, how can this be implemented?

I attempted to introduce an if statement prior to the ternary operation but it did not behave as anticipated:

fConvertValuesToArrays(obj) {
    for (const i in obj) { 
      if ( i.likes || i.dislikes ) {
        obj[i] = Array.isArray(obj[i]) ? obj[i] : [obj[i]];
      } 
    }
    return obj;
  },

Answer №1

To determine if the current key is present in the array aNamesToMatch, you can utilize the includes() method.

const oData = { 
  name: 'Hound', 
  weapon: 'sword', 
  likes: 'Chicken, Arya, Revenge', 
  dislikes: 'Fire, Mountain, Lannisters'
};
const aNamesToMatch = [ 'likes', 'dislikes' ];
function fConvertValuesToArrays(obj,keys) {
   
    for (const i in obj) { 
      if (keys.includes(i)) {
        obj[i] = Array.isArray(obj[i]) ? obj[i] : [obj[i]];
      } 
    }
    return obj;
  }
console.log(fConvertValuesToArrays({...oData},aNamesToMatch))

Answer №2

In order to streamline the process, consider iterating over just the aNamesToMatch array instead of the entire object. Transform each matching property in the object into an array:

const aNamesToMatch=['likes','dislikes'],
      oData={name:'Hound',weapon:'sword',likes:'Chicken, Arya, Revenge',dislikes:'Fire, Mountain, Lannisters'};

function fConvertValuesToArrays(obj, keys) {
  for (const key of keys) {
    if (!Array.isArray(obj[key]))
      obj[key] = [obj[key]]
  }
  return obj;
}

console.log(fConvertValuesToArrays(oData, aNamesToMatch))

To handle cases where a key from the array may not exist in the object, you can first check for its presence before making any modifications:

if (key in obj && !Array.isArray(obj[key])) {
}

Answer №3

Implement this modification

if(i === 'thumbsUp' || i === 'thumbsDown')
  { 
  obj[i] = Array.isArray(obj[i]) ? obj[i] : [obj[i]]; 
  }

This function will validate whether the key is thumbsUp/thumbsDown and generate an array if it matches.

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

Learn the process of assigning a value to a dynamically created textbox using JavaScript in code behind

To create a textbox in the code behind, I use the following method: TextBox txt = new TextBox(); txt.ID = "txtRef" + count + dr["DataField"].ToString(); div.Controls.Add(txt); I have been attempting to set the value for this textbox within a jQuery funct ...

What is the best way to display a nested Array inside another Array using React?

I'm currently working on a currency converter project where I need to display a list of currencies and their values. Here is an example of the data structure I am receiving from an API using Axios: Object {type: "li", key: "0", ref: null, props: Obje ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

Are Node environment variables persistent?

First Example: package.json Scripts "scripts": { "start": "node app.js", "test": "NODE_ENV=test mocha --reporter spec" }, Command to Run Test: if (process.env.NODE_ENV === "test") { cons ...

Remove browser data in PhoneGap / Prevent PhoneGap from utilizing cookies

Currently, I am in the process of creating a login system for my mobile application. After logging in to my server, it sends back a JSESSIONID that I can utilize for further authentication. The issue I am encountering is that PhoneGap is automatically st ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

"Unpredictable behavior observed with useSWR hook or potential issues with outdated closure function

Within my React functional component, I have implemented a Lesson Video Player that functions similarly to Instagram Stories. Each lesson contains videos ("clips") with interactive elements that trigger a multiple-choice quiz for the user. Below is a simpl ...

Creating an array of future dates using Moment.js

I am trying to use moment.js to create an array of the next 12 months, starting from the current month. For example, let's say the current month is December: var monthsArray = [ "December", "January", "February", "March", [...] "November" ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

The onprogress event for the XMLHttpRequest object threw an error due to an Uncaught SyntaxError, indicating

I have implemented an ajax function successfully However, I am facing an issue where when using onprogress, I sometimes receive incomplete HTML response and the console displays Uncaught SyntaxError: Invalid or unexpected token but the function still cont ...

Implement a loop using $.each along with conditional statements utilizing if with $.getJSON

Struggling with the usage of $.each and unable to figure out how to properly print all the data from my JSON file. Additionally, I've encountered issues with the if statement as well - no matter what approach I take, I can't seem to get any data ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

Unlocking the Power of Strapi v4: Leveraging Context within a Service

By creating a custom controller in Strapi, convenient access to a Context object is granted. This allows for retrieving the current user and utilizing the user's data as needed: module.exports = createCoreController("api::event.event", ({ st ...

Duplicate entries in the angular-ui Calendar

I've implemented the Angular-UI calendar to showcase some events. My activity controller interacts with the backend service to fetch the data, which is then bound to the model. //activity controller $scope.events = []; Activities.get() ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

"Learn the simple trick to quickly deactivate an anchor tag in just one easy

I have a navigation bar with items listed in an unordered list: <ul id="mainN" class="nanGroup" ng-show="lCntr.only == 'mainNav'"> <li > <a class="btn btn-small btn-revert" ng-click="lCntr.profile()"></a> &l ...

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...

unable to retrieve element values using class names

I have created multiple h1 elements with the same class names listed below. <h1 class="h1">One</h1> <h1 class="h1">Two</h1> <h1 class="h1">Three</h1> <h1 class="h1">Four</h1> I have also added a button that ...