Object array clone with subset of properties

后端 未结 3 1330
执笔经年
执笔经年 2020-12-18 09:40

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?

UPDATE

相关标签:
3条回答
  • 2020-12-18 09:48

    using Object Destructuring and Property Shorthand

    let array = [{ a: 5, b: 6, c: 7 }, { a: 8, b: 9, c: 10 }];
    let cloned = array.map(({ a, c }) => ({ a, c }));
    
    console.log(cloned); // [{ a: 5, c: 7 }, { a: 8, c: 10 }]
    
    0 讨论(0)
  • 2020-12-18 10:02

    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']);
    

    The result will be :

    [
       { name : 'khalid', city : 'ifrane' },
       { name : 'Ahmed', city : 'Meknes' }
    ]
    
    0 讨论(0)
  • 2020-12-18 10:11

    Performance-wise, that would be the most efficient way to do it, yes.

    0 讨论(0)
提交回复
热议问题