javascript/typescript - conditionally adding an item to an object

If I have an object called userData = {..}

and I need to create another object, userDataB, with properties a, b, c, and d from userData but only if they are defined. One way to achieve this is by using the following approach:

userDataB = {}
if(userData.a){userDataB.a = a};
if(userData.b){userDataB.b = b};
...

Is there a cleaner way to accomplish this task, perhaps leveraging ES5 or ES6 features?

Answer №1

Here's another helpful tip:

const object1 = {
    a: 'string',
    b: 42,
    c: true,
    d: undefined
};
let object2 = Object.assign(
    ...Object.keys(object1).map(key =>
        object1[key] !== undefined ? { [key]: object1[key] } : {}
    )
);

Try this as well:

let object2 = Object.assign(
    ...Object.entries(object1).map(obj =>
        obj[1] !== undefined ? { [obj[0]]: obj[1] } : {}
    )
);

And consider this option too:

let object2 = Object.entries(object1).reduce(
    (acc, val) => (val[1] !== undefined ? Object.assign(acc, { [val[0]]: val[1] }) : acc),
    {}
);

Answer №2

Utilize `JSON` methods to automatically remove any `undefined` properties:

var data = {
  x: "x",
  y: true,
  z: undefined,
  w: 5
};

var newData = JSON.parse(JSON.stringify(data));

console.log(newData);

Answer №3

Simply utilize Object.assign() to duplicate it into a fresh object:

var data = {
  x: 10,
  y: 20,
  z: 30
}
dataCopy = Object.assign({}, data);
console.log(dataCopy);

When dealing with undefined or null values:

var data = {
  x: 100,
  y: null,
  z: undefined,
  w: 400,
  v: 500
}
var dataCopy = Object.assign({}, data);
Object.keys(dataCopy).forEach((key) => (dataCopy[key] == null) && delete dataCopy[key])
console.log(dataCopy);

Answer №4

If you have a specific situation, this code snippet could be helpful:

const filteredObject = Object.keys(originalObject).reduce((result, key) => {
  if(originalObject[key] != undefined){ // customize this condition
    result[key] = originalObject[key];
  }
  return 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

Opening a new tab on any webpage with C# Selenium

Is there a foolproof way to open a new tab when using Selenium? Trying to use an action method has proven unsuccessful Actions a = new Actions(driver); a.KeyDown(OpenQA.Selenium.Keys.LeftControl); a.SendKeys("t"); a.KeyUp(OpenQA.Selenium.Keys.L ...

Execute a simulated click function in JavaScript without causing the viewport to move

I have successfully implemented a sticky add to cart feature on my Shopify store. However, there seems to be an issue where clicking on the variations in the sticky area also triggers the same variations on the product page, making it difficult for users t ...

Chrome browser causing issues with Bootstrap Modal functionality

Hello everyone, I've encountered an issue with the bootstrap 3 modal not functioning correctly in Chrome or Edge browsers. Interestingly, the modal works perfectly fine in FireFox. It's worth mentioning that the modal does briefly appear for a s ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

Refresh the project once logged in using angular

Thank you in advance for your response. I am facing an issue with monitoring user activity and automatically logging them out after a certain period of inactivity. I have successfully implemented this feature in my app.component.ts file, however, it only s ...

Boost the frequency of updates in Meteor.observe

When Python writes to a database (mongo) every second in the setup, Meteor.js is expected to react immediately to the new record insertion. Issue: However, the use of cursor.observe() results in the console outputting only 4-5 seconds after the new record ...

Retrieving a property of an object within an array using JavaScript in AngularJS

Seeking advice on how to calculate the total price of products in an array when working within a callback function. Is there a method similar to myArray.(intheobject).price? Or is there a way to handle callbacks effectively to achieve accurate results? th ...

Omitting certain values in jackson

I am currently working with Object Mapper and I am seeking a way to exclude certain fields based on specific values. Imagine having an object structured like this: public static class Data { int id; int value; } Let's assume that the value ...

Is there a way to trigger a function in an AngularJS controller from a Backbone controller?

I've been working on an application that was originally developed using backbone and jQuery, but we had to incorporate new modules built with angular to meet client requirements. Routing in the application is handled by backbone route, and we have suc ...

Manipulating data in a C# application using JSON

I am currently developing a desktop application for managing requests and responses. So far, I have successfully implemented GET requests, but now I need assistance in understanding how to handle JSON requests and responses. Once I can parse the JSON dat ...

Is selectpicker acting up?

Currently, I am troubleshooting a filter feature on a website that utilizes jQuery with JSON data. Everything was functioning properly until recently when an error started appearing: The selectpicker function is not recognized I would greatly appreciat ...

React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic. {MEMBERSHIPS.map((mItem, index) => ( <TableCell className="text-uppercase text-center" colSpan={2} padding="dense" ...

Whenever I try to make a JSON HttpWebRequest, it consistently results in

I attempted to create a request to test the functionality of allowing people to pay through an invoice. Since I have never made an API call with JSON data before, I decided to go through some documentation and Stack Overflow questions. I came across this ...

Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code: module.exports.validateToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

Exploring the possibilities in Bootstrap 5.3: Modifying the maximum width of an individual tooltip

Is there a way to modify the maximum width of a specific Bootstrap Tooltip without affecting the others? I do not utilize Sass or SCSS, and have attempted various methods outlined in the documentation: tooltip-max-width="300px" bs-tooltip-max-wid ...

Tips for accessing Firebase document fields with Angular Firestore (version 7)

My current task involves retrieving a Firebase document property based on the specified model: After successfully locating a document with this code snippet: //Users - collection name, uid - document uid. I am attempting to access the isAdmin property u ...

The Ocelot API Gateway is a powerful tool for managing

I encountered an issue while working on my API gateway project. I initially installed the latest version of Ocelot (16.0.1), but it did not function correctly. The problem was resolved by reverting back to Ocelot version 15.0.6, while keeping my .NET Core ...

Rotating a specific part of a model in THREE.js

Whether it's feasible to adjust the position or rotation of a component within an OBJ (or similar format) model. Can one manipulate a single model instead of needing multiple ones? What is the optimal approach to achieve this goal effectively? Appreci ...

How can I retrieve the chosen value from an AJAX combobox using JavaScript in an ASP.NET C# application?

How can I retrieve the selected value from an AJAX combobox item using JavaScript in ASP.NET C#? Below is the code snippet: <asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssCla ...