简体   繁体   English

用Java编写部分复制对象的代码的优雅方法?

[英]Elegant way to code partially copy objects in Javascript?

I have a javascript object that represents form fields. 我有一个表示表单字段的JavaScript对象。 about 70% of these fields have to be copied in some objects for sending to server, other fields are for UI usage. 这些字段中约有70%必须复制到某些对象中才能发送到服务器,其他字段则用于UI。 Presently I clone objects by manually creating assignments for each field, that result in rather not nice structures, as shown below. 目前,我通过为每个字段手动创建分配来克隆对象,这导致结构不太好,如下所示。 Note that I would keep field names identical for parts being copied. 请注意,对于要复制的部分,我将保持字段名称相同。

var contData = {
                ContainerType: data.ContainerType,
                ProjectIds: data.ProjectIds,
                PrivateToProjects: data.PrivateToProjects,
                DimensionType:data.DimensionType,
                MetricsX: data.MetricsX,
                MetricsY: data.MetricsY,
                Parent:data.Parent,
                ContainerName:data.Prefix
            };

What would be the best way to code cloning part of object, just specifying list of fields to clone/not to clone, such as some useful helper function? 仅指定要克隆/不克隆的字段列表(例如一些有用的辅助函数),对对象的部分进行编码的最佳方法是什么?

I also use angular and jquery. 我也使用angular和jquery。

After ES6, you could 在ES6之后,您可以

let { ContainerType, ProjectIds } = data  // the fields you want
let partiallyCopy = { ContainerType, ProjectIds }
console.log(partiallyCopy)  // { ContainerType: "...", ProjectIds: "..." }

And if you need most fields, you could 如果您需要大多数领域,则可以

let { ContainerType, ProjectIds, ...rest } = data  // the fields you don't want
let partiallyCopy = rest
console.log(partiallyCopy)  // the object excludes ContainerType and ProjectIds

You could create a custom function to clone your object partially with a filter function. 您可以创建一个自定义函数,以使用过滤器函数部分克隆对象。

It could be something like this as the very simple version. 可能是像这样的非常简单的版本。

function filteredClone(sourceObj, filterFunction){
  var destObj = {};
  for(var i in sourceObj){
    if(filterFunction(sourceObj[i])){
      destObj[i] = sourceObj[i];
    }
  }
  return destObj;
}

And you can call it like the following assuming that you don't want "name" and "surname" fields to be copied. 假设您不想复制“名称”和“姓氏”字段,则可以像下面这样调用它。

var dest = filteredClone(source, function(v){
   return ["name","surname"].indexOf(v) !== -1;
});

There are a couple of more sophisticated samples in the answers to the following question. 以下问题的答案中有两个更复杂的示例。

Deep clone without some fields 没有某些字段的深层克隆

One method is to define properties on objects. 一种方法是定义对象的属性。 IE9 is the first IE to support this. IE9是第一个支持此功能的IE。

var obj = {};
Object.defineProperty(obj, "no1", {enumerable: false, value: "", writable: true, configurable: true});
Object.defineProperty(obj, "no2", {enumerable: false, value: "", writable: true, configurable: true});

obj.yes1 = "foo";
obj.yes2 = "bar";
obj.no1 = "baz";
obj.no2 = "quux";

jsfiddle jsfiddle

99.9% of clone functions will loop over the keys, and only enumerable keys will show up, so they only copy enumerable keys. 99.9%的克隆功能将在键上循环,并且只会显示可枚举的键,因此它们仅复制可枚举的键。 This is the same reason why, eg toString doesn't show up when looping over an object's keys. 这就是为什么循环遍历对象的键时,例如toString不显示的相同原因。

This can be abstracted to allow defining data and temporary values. 可以将其抽象化以允许定义数据和临时值。

function makeType(description, data) {
    if (arguments.length === 1) {
        return function (data) {
            return makeType.call(this, description, data);
        };
    }

    var obj = {};
    data = data || {};
    for (var key in description) {
        if (description[key] === true) {
            obj[key] = data[key]
        } else {
            Object.defineProperty(obj, key, {
                enumerable: false,
                value: data[key],
                writable: true,
                configurable: true
            });
        }
    }
    return obj;
}

var makeYesNo = makeType({
    yes1: true,
    yes2: true,
    no1: false,
    no2: false
});

var obj = makeYesNo({
    yes1: "foo",
    yes2: "bar",
    no1: "baz",
    no2: "quux"
})

fiddle 小提琴

暂无
暂无

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

相关问题 有没有办法复制 javascript 中的对象数组? - Is there a way to copy an array of objects in javascript? 在 JavaScript 中,有一种优雅的方法可以合并两个对象并总结任何共同属性? - In JavaScript there an elegant way to merge two Objects and sum any common properties? 有没有比较优雅的方法来比较两个对象是否存在于javascript中? - Is there an elegant way to compare two objects for whether they exist in javascript? 深度复制对象的最有效方式javascript - most performant way to deep copy objects javascript 有没有更优雅的方法可以用javascript编写呢? - Is there a more elegant way to write this in javascript? 如何以最优雅的方式从javascript中的对象数组中获取最大值? - How to get the largest value from array of objects in javascript, in the most elegant way? 将带有对象和其他字段的嵌套 arrays 上传到 Firestore 的优雅方法是什么? (Node.js,Javascript) - What's an elegant way to upload nested arrays with objects and other fields to Firestore? (Node.js, Javascript) 如果存在则更新或向对象数组添加新元素 - javascript + lodash 中的优雅方式 - Update if exists or add new element to array of objects - elegant way in javascript + lodash 当声明具有多个级别的多个javascript对象时,最优雅的方法是什么? - When declar multiple javascript objects with more than one levels, what is the most elegant way? 按嵌套属性对对象进行分组的更优雅的方式 - More elegant way to group objects by nested attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM