Modify the attributes of items in a way that is unchangeable for certain identifiers

If any pre-defined keys have an empty string value, I want to replace it with a null value.

For example:

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

Should be updated to:

const foo = {
  first: null,
  second: 'bar',
  third: '',
  fourth: null,
  fifth: '',
}

Now we can use the following function successfully:

const normalize = (payload, keys) => {
  const clone = { ...payload }
  Object.entries(payload).forEach(([key, value]) => {
    if (keys.includes(key) && value === '') {
      clone[key] = null;
    }
  });
  return clone;
}

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

console.log(normalize(foo, ['first', 'third']));

However, the 'clone' variable could be improved.

One common method for this is using Object.assign().

Would you like to explore this approach?

Answer №1

Here's an alternative method that involves looping through the keys argument array. It is more efficient to focus on only the necessary keys in the object.

const convertEmptyStringToNull = (data, keys) => {
  return keys.reduce((result, key) => {
    (result[key] === '') && (result[key] = null)
    return result;
  }, { ...data })
}

const exampleData = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

console.log(convertEmptyStringToNull(exampleData, ['first', 'third']));

Answer №2

Is it possible to iterate through the array and update the object values?

const data = {
  name: 'John',
  age: 25,
  city: 'New York',
}

function modifyObject(obj, keys) {
  const newObj = {...obj}
  for (let i = 0; i < keys.length; i++) {
    newObj[keys[i]] = null;
  }
  return newObj;
}
console.log(modifyObject(data, ['age', 'city']));

Answer №3

If you want to eliminate specific keys from an object, you can iterate through the object using for...in and then use some() method to check if the key matches the desired ones.

const data = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

const filterKeys = ({...obj}, keys) => {
  for (let key in obj) {
    if(keys.some(k => k === key)) {
      obj[key] = null;
    }
  }

  return obj;
}

console.log(filterKeys(data, ['third', 'fifth']));

Answer №4

What do you think of this?

If you look at your keys in norm, the function will return a new mapping that is either null if it needs to be normalized or just an empty string.

const obj = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}, norm = ['third', 'fifth'];

const normalizeFunction = (payload, keys) => {
    return keys.reduce((acc, key) => acc[key] === "" ? (acc[key] = null) : acc, {...payload})
}

The result will be:

const norm = ['third', 'fifth'];
normalizeFunction(obj, norm)

{first: "", second: "bar", third: null, fourth: "", fifth: null}

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

Encountered an issue while trying to establish a connection between node.js and MongoDB

db connection error querySrv ENOTFOUND _mongodb._tcp.nodeapi.vlvom.mongodb.net (node:7720) UnhandledPromiseRejectionWarning: Error: querySrv ENOTFOUND _mongodb._tcp.nodeapi.vlvom.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) (Us ...

Looking to convert files like text or images into binary format using Node.js?

I'm struggling to find a solution for converting any type of file (text, image, etc) into binary format using Node. Can anyone provide some guidance on how to accomplish this task? ...

Steps for establishing a connection to a MongoDB database on Heroku using mongoose

Everything is running smoothly with my app locally and it can successfully connect to the local database. However, when I attempt to run it on Heroku, I encounter the following error: 2014-04-17T06:32:23.404458+00:00 app[web.1]: > <a href="/cdn-cgi ...

The indicated processing instruction is incompatible with the provided payment source. PayPal's hosted fields for credit card payments do not support this specific processor

I'm currently working on integrating credit card payments with hosted fields into my checkout process. However, I keep encountering an UNPROCESSABLE_ENTITY error when making the confirm-payment-source request through the PayPal JS SDK. Here is the co ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

The compiler mistakenly infers an incorrect type while utilizing a default value for a discriminated union type

I am currently working on a simplified component: export type BaseProps = { size?: 'xs' | 'sm' | 'md' | 'lg'; } type ButtonAsButtonProps = Omit<React.ComponentPropsWithoutRef<'button'>, ' ...

Disable the Layout Component in Next.js for certain pages directly from the _app.js file

Is there a way to exclude a specific page from being wrapped with the Layout component in _app.js? For instance, with pages named pages/home and pages/about, how can I prevent the Layout component from wrapping the pages/home page? pages/_app.js import & ...

Error while compiling Q_PROPERTY

Current Environment : Qt 5.8 MSVC2015 64bit, Windows 7 64 bit. I have successfully called a C++ method from Java Script. However, I encountered an issue when trying to retrieve the return value of the C++ method in JavaScript. To address this, I attempt ...

Encountering mixed content error on webpack development server

My React based website is currently running on Cloud9 using webpack-dev-server, which serves content over https. However, I have encountered an issue when attempting to make ajax (network) requests to external http links. The error message I receive is: ...

The Mystery of jQuery Isotope Plugin: Why Can't I Add "display:none" Inline?

I'm currently in the process of integrating Isotope into my latest Wordpress theme. However, I've encountered an issue where it's not appearing on the page due to some external factor adding an inline style (display:none) to the main isotope ...

Vue Router Guard Failing to Work Properly After Page Reload

I have implemented a router guard to protect certain pages in my app. The goal is for users to be prompted to log in when attempting to access these protected pages. Currently, the guard works as expected within the app itself. However, if a user refresh ...

The AngularJS directive within a directive is failing to properly initialize the scope value

In my current setup, I am working with a controller that contains the value $scope.colorHex. As an example, I am utilizing the directive colorpickerTooltip, and within its template, I am calling another directive: <colorpicker ng-model="colorHex">&l ...

Unable to modify the appearance of text on the canvas

Trying to customize the font style of canvas text with Press Start 2P The URL has been imported into a CSS file as follows: @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap'); .canvasClass{ font-family: ...

Error: Attempting to access 'push' property on an undefined object

Encountered an Error After implementing the useNavigate function, I successfully resolved the issue. let params = useParams(); let navigate = useNavigate(); const dispatch = useDispatch(); const productId = params.id; const [qty, setQty] = useStat ...

Is it possible to display two separate pieces of content in two separate divs simultaneously?

import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <span>Is React a JavaScript library for creating user interfaces?</span>, document.getElementById("question1") ) ReactDOM.render( <form class="options"> ...

fetch Active Directory user details using React

I'm working on a React web application. I need to pull user information from Active Directory and verify if the user belongs to a specific AD group. Is this achievable? What would be the best approach to create an API for this integration? ...

Encountering numerous errors when attempting to incorporate lottie-web into my JavaScript file

I am in the process of creating a unique audio player for my website utilizing HTML, CSS, and JavaScript. I encountered some challenges while trying to get it to work effectively on Codepen as well as my text editor. The animations were not functioning pro ...

Tips for passing a state value to a different state when initializing in react js

I need some help with passing a state value called imagesArray to another state named tabData. It seems like the value is coming up as undefined. Below is the code snippet, can you please point out what I might be doing wrong? constructor(props) { s ...

The .map function doesn't seem to be functioning properly in the React application

I am facing an issue with the .map method of the object from the API I imported. Despite being able to see the object in the browser console, I cannot interact with it. This component is called "races" const BASE_URL = "https://www.dnd5eapi.co/api/races"; ...

Dynamically update a form with steps using JQuery-steps and send all objects to the controller

In the context of a form, it is possible to dynamically add between 1 to n records before passing it to the controller with data. The following represents the ViewModel for the form: public class AddFieldDataViewModel { public int SampleID { get; se ...