Conditionally adding properties to JavaScript object

conditionally add object to array javascript
add property to object javascript
es6 add property to object
conditional destructuring javascript
javascript conditional json
javascript set property if exists
conditional array destructuring javascript
ternary operator inside object javascript

Is there a more concise or readable way of doing this?

var foo={a:111,c:333, somePropertyThatShouldntBeAdded:'xxx'};
var myobj={x:1,y:2,z:3};
if(foo.a){myobj.a=foo.a;}
if(foo.b){myobj.b=foo.b;}
if(foo.c){myobj.c=foo.c;}

EDIT. Context why I am doing this is below.

var obj={value:this.text,css:{color:'#929292',margin:'1px 0px'}};
if(this.width){obj.css.width=this.width;}
if(this.type){obj.type=this.type;}
if(this.id){obj.id=this.id;}
var input=$('<input/>',obj)

You could use a simple loop-based approach:

var foo={a:111,c:333, somePropertyThatShouldntBeAdded:'xxx'};
var myobj={x:1,y:2,z:3};

['a','b','c'].forEach(function(key) {
    if(key in foo) {
        myobj[key] = foo[key];
    }
});

Notice how I used the in keyword. Your current solution will not work if the value of a property is (e.g.) false or 0.

Additionaly, to get better solutions, provide some context: why are you conditionally copying properties? Perhaps you can avoid this to begin with.

In Javascript, how to conditionally add a member to an object , In Javascript, how to conditionally add a member to an object? I would like to create an object with a member added conditionally. The simple approach is: var a = {}; if (someCondition) a. Now to Object 'obj' we would like to add a property or key, usually this is how we add a property to Object literal in javascript: let obj = {}; obj . property1 = ' value1 ' ;


You can use the ternary operator like this:

myobj.a = foo.a ? foo.a : undefined;

Though its not exactly the same as the if statement you have, because you'll have {a: undefined} instead of {}. The difference would show up if you ever enumerated the keys of your object.

Edit:

@hindmost has a good suggestion in the comments. You could improve it further with underscore.js:

_.extend(myobj, _.pick(foo, ['a', 'b', 'c']));

The shortest way to conditional insert properties into an object literal , Conditionally adding properties into an object could be done in many ways. Tagged with javascript, objects, beginners, specification. In this post, we will see how to add a property to an object in JavaScript. 1. Dot notation. A simple approach is to use the dot notation with assignment operator to add a property to an existing object. The syntax is: object.property = value.


You could use jQuery's extend, then delete the properties you don't want:

function extendExcept(sourceObject, targetObject, except) {
    var target = $.extend(sourceObject, targetObject);
    except.forEach(function(key) {
        delete target[key];
    });
    return target;
}

You could call it like:

var foo={a:111,c:333, somePropertyThatShouldntBeAdded:'xxx'};
var myobj={x:1,y:2,z:3};
myobj = extendExcept(foo, myobj, ["somePropertyThatShouldntBeAdded"]);

Working Example

Adding object properties conditionally with ES6, Adding a property to an object​​ You can basically do it like in the following code. const person = { firstName: "Max", }; person. lastName = ""; But imagine the lastName should just be added if there is a specific conditional. Conditionally adding properties into an object could be done in many ways. This article explain why and how the shortest known solution works!. Tagged with javascript, objects, beginners, specification.


var foo = {
    a: 111, 
    c: 333, 
    somePropertyThatShouldntBeAdded: 'xxx'
}; 

var myObj = {
    x: 1, 
    y: 2, 
    z: 3
}; 

for(var key in foo) {
    if(key === 'somePropertyThatShouldntBeAdded') {
        continue; 
    }
    myObj[key] = foo[key]; 
}

How to conditionally build an object in JavaScript with ES6, Docker Remove Image Tar GZ What is a CSV File? CSS Flexbox Linux Commands JavaScript Map What is HTTPS? Python List Append What is  Accessing JavaScript Properties. The syntax for accessing the property of an object is: objectName.property // person.age. or. objectName [ "property" ] // person ["age"] or. objectName [ expression ] // x = "age"; person [x] The expression must evaluate to a property name.


With the introduction of the spread operator in ES2018 you can do something like this.

const original = {
    first: null,
    second: 'truthy'
};

const conditionalObject = {
  ...( original.first && { first: original.first }),
  ...( original.second && { second: original.second })
};

In the conditionalObject we first check if the property we want to add from the original is truthy, if it is we spread that property with its value into the new object.

If the property from the original object is falsy, the && short circuits and the property is never spread into the new object.

You can read a more detailed explanation here

The new conditionalObject will look like this

{
    second: 'truthy'
}

Adding object properties conditionally with EcmaScript 6 (ES6), Adding a property to an object is quite easy in JavaScript. You can basically do it like in the following code. But imagine the lastName should just  Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows: myCar['make'] = 'Ford'; myCar['model'] = 'Mustang'; myCar['year'] = 1969;


Conditionally adding entries inside Array and object literals, Cover of book “JavaScript for impatient programmers” Conditionally adding entries inside Array and object literals shows how you can conditionally add elements inside Array literals and properties inside object literals. Your current solution will not work if the value of a property is (e.g.) false or 0. Additionaly, to get better solutions, provide some context: why are you conditionally copying properties? Perhaps you can avoid this to begin with.


Adding properties to javascript object literal conditionally, How to add keys/properties to an object in javascript conditionally with help of latest es6 spread operator and short circuit evaluation. Adding object properties conditionally with EcmaScript 6 (ES6) This was a tweet recently by an engineer from Google who is working on the V… This app works best with JavaScript enabled. Web Dev Stories


How to conditionally add a member to a JavaScript object?, This article describes how to add a member to a JavaScript object only if a a solution that can handle conditional adding when declaring the object. As you can see we set all the attributes of the second object, but only the  If you've worked with objects in JavaScript, you may have come across situations where you need to optionally add values to an existing object. To illustrate my example, I'd like to welcome the Spice Girls to this corner of the internet.