简体   繁体   English

从对象拼接属性?

[英]Splicing properties from an object?

Is there a utility (jquery, lodash, etc) that extracts properties from an object to another object and then deletes them from the original object? 是否有实用程序(jquery,lodash等)将一个对象的属性提取到另一个对象,然后从原始对象中删除它们? Similar to Array's splice? 类似于Array的接头吗?

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

result: 结果:

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

You could use a function for it, which iterates the keys and returns a new objectc and deletes the keys from the source object. 您可以为此使用一个函数,该函数迭代键并返回一个新的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); 

An alternative way is to use underscore's _.object() method to create a quick custom extract fn: 另一种方法是使用下划线的_.object()方法创建快速的自定义extract fn:

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

DEMO DEMO

Here's how custom extract function may be defined: 定义自定义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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM