1

Suppose there are two objects

source = {
   name: "A",
   address: {
      city: "B",
      zipcode: "C"
   },
   car: {
      make: "D",
      model: "E"      
   }
};

target = {
   name: "",
   address: {
      city: ""
   }
};

Now I want to copy all data from source over to target. However, copying must only take place, if the corresponding property already exists in the target. It is something like jQuery's extend, without adding new properties. With the above data the result will be...

target = {
   name: "A",
   address: {
      city: "B"
   }
};

How can this be achieved easily?

4

2 に答える 2

3

これはそれを行う必要があります:

function extend(target, source) {
    for (var prop in source)
        if (prop in target) // <== test this
            if (typeof target[prop] === "object")
                extend(target[prop], source[prop]);
            else
                target[prop] = source[prop];
}

免責事項:この単純なものは、配列、列挙可能なプロトタイププロパティ、値では機能しませんnull…</ sub>

最も外側のループを次のように変更することもできます

    for (var prop in target)
        if (prop in source)

2つのオブジェクトのどちらが、列挙するプロパティが少ないかによって異なります。

于 2013-03-04T19:54:48.733 に答える
1

You could just loop through target and then grab the values from `source. I'd suggest a recursive function, since your object may have multiple sub-objects.

function fill_in_values(target, source){
    for(var prop in target){
        if(typeof target[prop] === 'object'){
            fill_in_values(target[prop], source[prop]);
        }
        else{
            target[prop] = source[prop];
        }
    }
}
于 2013-03-04T19:55:28.357 に答える