Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Add property to object literal and return

I have object literal what I consider as base object:

var obj = {
   key1   : 'value1',
   key2   : 'value2'
}

and would like to use this object and pass it to function with extention like

myFunction( obj + { key3 : 'value3' } );

// param became:
{
   key1   : 'value1',
   key2   : 'value2',
   key3   : 'value3'
}

or

myFunction( obj + { key2 : 'new value2' } );

// param became:
{
   key1   : 'value1',
   key2   : 'new value2'
}

+ operator is not correct for it. How I can do it? Is it a way ?

EDIT: Do you want to permanently alter obj? - No, I would like to able to reuse it for next call as base.

like image 725
bensiu Avatar asked Dec 21 '11 22:12

bensiu


People also ask

How do I add properties to an object in JavaScript?

Javascript adds a property to Object To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.

How do you conditionally add property to an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

How do you assign a value to an object property?

Object.assign() Method Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.

How do I add a new property to an existing object in TypeScript?

To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!


2 Answers

With ES2018 or TypeScript 2.1 you can use the object spread syntax.

// properties on the right overwrite properties on the left

// Overwrite properties from obj
myFunction( { ...obj, key3: 'value3' } );

// Don't overwrite properties from obj
myFunction( { key3: 'value3', ...obj } );

With ES2015 you can use Object.assign.

// Object.assign(a, b, c, ..) - copy properties from b to a, then from c to a etc.

// Overwrite properties from obj
myFunction( Object.assign({}, obj, { key3: 'value3' }) );

// Don't overwrite properties from obj
myFunction( Object.assign({ key3: 'value3' }, obj) );

Demo

var obj = { key1: 'value1', key2: 'value2'}

console.log('-- Object Spread --');
console.log({ ...obj, key3: 'value3' });
console.log('overwrite');
console.log({ ...obj, key2: 'NEW2' });
console.log('no overwrite');
console.log({ key2: 'NEW2', ...obj });

console.log('-- Object Assign --');
console.log(Object.assign({ key3: 'value3' }, obj));
console.log('overwrite');
console.log(Object.assign({}, obj, { key2: 'NEW2' }));
console.log('no overwrite');
console.log(Object.assign({ key2: 'NEW2' }, obj));


console.log('-- Original Object unchanged --');
console.log(obj);
like image 72
frido Avatar answered Oct 21 '22 05:10

frido


If you're okay with altering obj, just change it before you pass it:

var obj = { /* stuff */ };

obj.key3 = 'value3';
myFunction(obj);

Do you want to permanently alter obj? - No, I would like to able to reuse it for next call as base.

Okay, so you need to make a copy of obj, and alter the copy — either before you call myFunction:

var obj = { /* stuff */ };
var extension = {key3: 'value3'};

myFunction($.extend({}, obj, extension));

or pass obj and the "extension" to myFunction:

var obj = { /* stuff */ };
var extension = {key3: 'value3'};

myFunction(obj, extension);

and have myFunction do the work:

function myFunction(base, ext)
{
    if (typeof base === 'object' && typeof ext === 'object')
    {
        base = $.extend({}, base, ext);
    }

    // rest of the function logic here
}

If you're already (or don't mind) using jQuery, $.extend() will be your best friend for the task.

like image 35
Matt Ball Avatar answered Oct 21 '22 04:10

Matt Ball