具有属性子集的对象数组克隆 [英] Object array clone with subset of properties

查看:97
本文介绍了具有属性子集的对象数组克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中将统一对象的数组克隆为一个具有每个对象的属性子集的最有效方法是什么?

What is the most efficient way in JavaScript to clone an array of uniform objects into one with a subset of properties for each object?

更新

这是最有效的方法还是有更好的方法? -

Would this be the most efficient way to do it or is there a better way? -

var source = [
    {
        id: 1,
        name: 'one',
        value: 12.34
    },
    {
        id: 2,
        name: 'two',
        value: 17.05
    }
];

// copy just 'id' and 'name', ignore 'value':
var dest = source.map(function (obj) {
    return {
        id: obj.id,
        name: obj.name
    };
});

推荐答案

首先定义一个克隆对象并返回属性子集的函数,

First define a function that clone an object and return a subset of properties,

Object.prototype.pick = function (props) {
   return  props.reduce((function (obj, property) {
        obj[property] = this[property];
        return obj;
   }).bind(this), {});
}

然后定义一个函数,该函数可克隆数组并返回每个对象的子集

Then define a function that clone an array and return the subsets of each object

function  cloneArray (array, props) { 
    return array.map(function (obj) { 
       return obj.pick(props);
    });
}

现在,我们假设您具有以下数组:

Now let's say you have this array :

var array = [
   { name : 'khalid', city : 'ifrane', age : 99 },
   { name : 'Ahmed', city : 'Meknes', age : 30 }
];

您需要调用该函数并传递您需要获得的属性数组作为结果

you need to call the function and pass the array of properties you need to get as result

cloneArray(array, ['name', 'city']);

结果将是:

[
   { name : 'khalid', city : 'ifrane' },
   { name : 'Ahmed', city : 'Meknes' }
]

这篇关于具有属性子集的对象数组克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆