0

What I am trying to do is create an object which has x number of properties in it along with y number of properties from another object I retrieve from calling another method. Is this possible to do?

ie Here is my pseudo code. Basically I want mydata to include all the properties from the object I get back from getMoreData() Maybe this is not possible but I have no idea how to do it if it is :(

var mydata = 
{
    name: "Joe Soap",
    dob: "01-01-2001",
    otherData: {
        hasCat: true,
        hasDog : false
    }

    var otherData = getMoreData();
    for(var prop in otherData)
    {
        create additional property in mydata for prop;
    }
}

function getMoreData()
{
    var moreData = 
    {
        middleName: "tom",
        location: "uk"
    }
    return otherData;
}
MayoMan
  • 4,757
  • 10
  • 53
  • 85
  • It seems you want what is called a **mixin** - http://lostechies.com/derickbailey/2012/10/07/javascript-mixins-beyond-simple-object-extension/. – Paul Grime Apr 05 '13 at 09:26
  • 1
    possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – Felix Kling Apr 05 '13 at 09:28
  • cheers, "merge" was the key word I should have been searching for :) – MayoMan Apr 05 '13 at 09:42

2 Answers2

0

You can't declare variables or use other statements like for in the middle of an object literal. You need to define the basic object first, and then add properties afterwards:

var mydata = {
    name: "Joe Soap",
    dob: "01-01-2001",
    otherData: {
        hasCat: true,
        hasDog : false
    }
};

var otherData = getMoreData();
for(var prop in otherData) {
    mydata[prop] = otherData[prop];
}

Also your getMoreData() function needs to return the moreData variable, not otherData:

function getMoreData() {
    var moreData = {
        middleName: "tom",
        location: "uk"
    }
    return moreData;
}

Demo: http://jsfiddle.net/nnnnnn/TQf5H/

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

In Addition to nnnnnn's Answer. Be careful that the above does only a shallow copy.

Meaning if you have an Object it gets copied by reference.

Here is a bit more advanced merge function. i'll explain it a bit more in detail later.

Merge Function


var merge = (function () {
    var initThis = this;
    return function () {
        var len = arguments.length - 1,
            srt, tmp;
        if ("function" === typeof arguments[arguments.length - 1]) srt = arguments[arguments.length - 1];
        else {
            srt = function (a, b, prop) {
                if (null === prop) return a;
                return a[prop];
            };
            len++;
        }
        var merge = this === initThis ? {} : this;
        for (var i = 0; i < len; i++) inner(arguments[i], merge);

        function inner(obj2, obj1) {
            var type = ({}).toString.call(obj2);
            if (type == "[object Object]") {
                if (!obj1) obj1 = {};
                if (typeof obj1 != "object") obj1 = (tmp = srt(obj1, obj2, null), tmp) === obj2 ? {} : tmp; //If obj2 is returned, set to empty obj to allow deep cloning
                for (var prop in obj2) {
                    var isObj = "object" === typeof obj2[prop];
                    if (!obj1[prop] && isObj) obj1[prop] = inner(obj2[prop]);
                    else if (obj1[prop] && isObj) obj1[prop] = inner(obj2[prop], obj1[prop]);
                    else if (obj1[prop]) obj1[prop] = srt(obj1, obj2, prop) || obj1[prop];
                    else obj1[prop] = obj2[prop];
                }
            } else if (type == "[object Array]") {
                if (!obj1) obj1 = [];
                if (typeof obj1 != "object") obj1 = (tmp = srt(obj1, obj2, null), tmp) === obj2 ? [] : tmp
                for (var i = 0; i < obj2.length; i++) if (!obj1[i] && typeof obj2[i] == "object") obj1[i] = inner(obj2[i]);
                    else if (obj1[i] && typeof obj2[i] == "object") obj1[i] = inner(obj2[i], obj1[i]);
                else if (obj1[i]) obj1[i] = (function (i) {
                        return srt(obj1, obj2, i)
                    })(i) || obj1[i];
                else obj1[i] = obj2[i];
            }
            return obj1;
        }
        return merge;
    };
})();

Sample Data


var target = {
    unique: "a",
    conflict: "target",
    object: {
        origin: "target"
    },
    typeConflict: "primitive",
    arr: [1, 5, 3, 6]
};
var mergeFrom = {
    other: "unique",
    conflict: "mergeFrom",
    object: {
        origin: "mergeFrom",
        another: "property"
    },
    typeConflict: ["object"],
    arr: [3, 2, 7, 1]
};

Usage


The merge function accepts n parameters.

And merges all passed Objects into one and returns it.

You can set a context with .call into which the Objects get merged.

A conflict function can be passed as last argument. Which gets called if an propertie already exists.

It gets called with 3 parameters.

a,b , prop where

a is the first object b is the second object prop is the property which gets merged currently.

If theres a type conflict. e.g value 1 is a primitive and value 2 an Object

prop is null


Example Calls


Calling the merge function with a context, other than the scope its in, it merges the Object into it.

merge.call(target,mergeFrom)

Calling it, passing a conflict function that always uses object b properties.

var result = merge(target,mergeFrom,function (a,b,prop) {  
    if (prop === null) return b  
    return b[prop]  
})

Calling it passing 3 Arrays and a conflict function that pushes the values into the first

var mergedArr = merge({arr:[1]},{arr:[2]},{arr:[3]},function (a,b,prop) {
  if (a[prop] != b[prop]) a.push(b[prop])
  return a[prop]
})

Heres an example on JSBin

Outputs


Example 1 - console.log(target)

{
    "arr": [1, 5, 3, 6],
    "as": "arguments",
    "conflict": "target",
    "more": "Objects",
    "object": {
        "another": "property",
        "origin": "target"
    },
    "other": "unique",
    "typeConflict": "primitive",
    "unique": "a"
}

Example 2 - console.log(result)

{
    "arr": [3, 2, 7, 1],
    "conflict": "mergeFrom",
    "object": {
        "another": "property",
        "origin": "mergeFrom"
    },
    "other": "unique",
    "typeConflict": ["object"],
    "unique": "a"
}

Example 3 - console.log(mergedArr)

{
    "arr": [1, 2, 3]
}
Moritz Roessler
  • 8,542
  • 26
  • 51