4

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)
5
  • 2
    jquery.extend(myobj, foo) Commented Apr 25, 2015 at 16:39
  • 3
    @hindmost somePropertyThatShouldntBeAdded might pose a problem. Commented Apr 25, 2015 at 16:39
  • @user1032531 Could delete myobj.somePropertyThatShouldntBeAdded afterwards? Commented Apr 25, 2015 at 16:43
  • @RGraham Guess the right answer, like always, depends on the actual circumstances. Do I have a bunch of properties to add and only one or two which shouldn't be, or the opposite. Commented Apr 25, 2015 at 16:46
  • @hindmost extend() looks like a good solution if some sort of filter could be applied to the foo to only return the applicable properties to add. Commented Apr 25, 2015 at 16:51

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Context provided to original post. Thanks for your reply.
1

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'
}

Comments

0

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']));

1 Comment

Btw underscore also provides a function _.omit what will be the opposite of _.pick
0

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

2 Comments

But what is the except property all ready exists on sourceObject?
@dev-null Valid point. I guess this depends on the requirements
0
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]; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.