具有属性子集的对象数组克隆

编程入门 行业动态 更新时间:2024-10-09 16:28:15
本文介绍了具有属性子集的对象数组克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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' } ]

更多推荐

具有属性子集的对象数组克隆

本文发布于:2023-11-29 10:51:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子集   数组   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!