In JavaScript, How to Conditionally Add a Member to an Object

In JavaScript, how to conditionally add a member to an object?

In pure Javascript, I cannot think of anything more idiomatic than your first code snippet.

If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says:

Undefined properties are not copied.

Therefore, you can write:

var a = $.extend({}, {
b: conditionB ? 5 : undefined,
c: conditionC ? 5 : undefined,
// and so on...
});

And obtain the results you expect (if conditionB is false, then b will not exist in a).

How to conditionally create object property in one line?

Create object property obj.foo if value exists (or any other condition)

&& operator returns second element if the first boolean condition is fulfilled

es6 spread operator ... does what it does)

const value = 'bar'

const empty = undefined

const obj = {
...value && { foo: value }, // read ...(value && { foo: value }) parenthesis are not necessary
...empty && { empty },
...(100 > 0) && { condition: 'true' },
...(100 < 0) && { condition: 'false' },
}

console.log(obj)

How to conditionally add properties to a javascript object literal

You've pretty much shown a use case for a constructor function instead of using an object literal:

function CustomObject(includeB) {
this.a = 1;
if (includeB) {
this.b = 2;
}
}

//has `a` only
var obj1 = new CustomObject(false);

//has `a` and `b`
var obj2 = new CustomObject(true);

After re-reading your question it appears that you've got limited access in modifying the function. If I'm understanding your question correctly you can only change a limited portion of the script:

function create(includeB) {
// modifications may be done here

// the rest may not change
return {
a : 1
}
}

var obj = create(false);
// obj must have property 'a' ONLY

var obj = create(true);
// obj must have properties 'a' and 'b'

If that's the case, then you could simply skip the later part of the function:

function create(includeB) {
if (includeB) {
return {
a: 1,
b: 2
};
}
return {
a: 1
};
}

Conditional adding object property in JavaScript

I would suggest you adding object properties conditionally with ES6 syntax like this.

const normalizeData = ({id, name = ""}) => {
const condition = !!name; // Equivalent to: name !== undefined && name !== "";
return {id, ...(condition && { name })};
}
console.log(normalizeData({id: 123, name: ""}));
console.log(normalizeData({id: 123, name: undefined}));
console.log(normalizeData({id: 123, name: "Phong_Nguyen"}));

Typescript/Javascript Conditionally Add members to object using spread op

Yes, it's happening exactly what you're thinking, this is why you need a reference from a previous value of the data object.

const test = {
...(someobj.field1 && { field1: someobj.field1 }),
...(someobj.nofield && { nofield: "yowzee" }),
...(someobj.data.datafield1 && { data: { dataField1: "woohoo" }}),
...(someobj.data.datafield2 && { data: { ...someobj.data, datafield2: "hooahh" }}), // doesn't overwrites the above.
};

By spreading someobj.data inside of itself, you are ensuring that it has his previous value.

Adding an object conditionally inside an array

From what I understood, you want to filter away all the elements of the array given a condition. What I would do is adding a new key to the object specifying if it should be displayed, and then filter & map.

const typesOfCards = [
{ name: "Card A", size: "Medium", action: "make", type: "typeA" },
...
];
return typesOfCards.filter(card => card.type === "typeA").map(({ name, size, action }) => (
<BuildCard name={name} size={size} action={action} />
));

Assign, and set js object property conditionally

Updated answer:

Here's how you can do it:

// Will result in { foo: 'foo', bar: 'bar'}

const item = {

foo: 'foo',

... true && { bar: 'bar' },

... false && { falsy: 'falsy' },

}

console.log(item)

Conditionally set an object property

Do it like this :

data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : undefined)
}

A property whose value is undefined isn't written when you stringify the object to JSON.


EDIT : It appears from the comments that there is no JSON involved in fact. OP is using $.ajax so $.param is probably used. $.param, unfortunately, does create an entry for properties whose value is undefined. So there's probably no solution without any supplementary line of code.



Related Topics



Leave a reply



Submit