0

The scenario is to dynamically add some properties to JavaScript object at once.

For example, there is an object "data"

var data = {
    PropertyA: 1,
    PropertyB: 2,
    PropertyC: 3,
}

Then add extra data to "data"

if(true){
    var extraData = {
        PropertyD: 4,
        PropertyE: 5,
        PropertyF: 6,
    }
} else {
    var extraData = {
        PropertyX: 4,
        PropertyY: 5,
        PropertyZ: 6,
    }
}

What is the best way or the easiest to add "extraData" to "Data"?

Salomon Zhang
  • 1,553
  • 3
  • 23
  • 41
  • See https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – RaphaMex Dec 04 '17 at 02:20
  • 2
    Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – ibrahim mahrir Dec 04 '17 at 02:25
  • `Object.assign(data, condition? extraDataDEF: extraDataXYZ);`. – ibrahim mahrir Dec 04 '17 at 02:30

3 Answers3

1
Object.assign(data, extraData);

If you don't want to mutate the value of data, you can do something like this instead:

var newData = Object.assign({}, data, extraData);
Giovanni Lobitos
  • 852
  • 7
  • 19
-1

The most modern approach would be to use ES6's spread:

const moreData = { ...data, extraData };

Alternatively this would be the traditional way of doing it:

var moreData = Object.assign({}, data, extraData);
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
-2

Here is a good way to do that:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
  $(function(){
       var data = {
            PropertyA: 1,
            PropertyB: 2,
            PropertyC: 3,
        };
        if(true){
            var extraData = {
                PropertyD: 4,
                PropertyE: 5,
                PropertyF: 6,
            };
        } else {
            var extraData = {
                PropertyX: 4,
                PropertyY: 5,
                PropertyZ: 6,
            };
        }

        var object = $.extend({}, data, extraData);

        console.log(object);

    });
</script>
slon
  • 1,002
  • 1
  • 8
  • 12