2017-02-23 79 views
2

是否有一個實用程序(jQuery的,lodash等),提取屬性從一個對象到另一個對象,然後從原始對象中刪除它們?與Array的拼接類似?從物體拼接屬性?

obj1 = {color:"red", age:"23", name:"cindy"} 
obj2 = extract(obj1, ["color","name"]) 

結果:

obj1 is { age:23 } 
obj2 is {color:"red", name:"cindy"} 

回答

2

你可以使用它的功能,它迭代鍵和返回一個新的objectc並刪除從源對象的鍵。

function extract(object, keys) { 
 
    return keys.reduce(function (o, k) { 
 
     o[k] = object[k]; 
 
     delete object[k]; 
 
     return o; 
 
    }, {}); 
 
} 
 

 
var obj1 = { color: "red", age: "23", name:"cindy" }, 
 
    obj2 = extract(obj1, ["color","name"]); 
 
    
 
console.log(obj1); 
 
console.log(obj2);

0

下面是如何定製extract函數可以被定義爲:

function extract(o, keys) { 
 
    var newObj = {}; 
 
    keys.forEach(function(k){ 
 
     if (o.hasOwnProperty(k)) { // check if a key exists in `source` object 
 
      newObj[k] = o[k]; 
 
      delete o[k];  // removing property from `source` object 
 
     } 
 
    }); 
 

 
    return newObj; 
 
} 
 

 
var obj1 = {color:"red", age:"23", name:"cindy"}, 
 
    obj2 = extract(obj1, ["color","name"]); 
 

 
console.log(obj1); 
 
console.log(obj2);

1

的另一種方式是使用下劃線的_.object()方法來創建快速定製extract FN:

function extract(properties, object) { 
    return _.object(properties, properties.map(prop => object[prop])); 
} 

DEMO