Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object array clone with subset of properties

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

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
    };
});
like image 731
vitaly-t Avatar asked Jun 05 '15 11:06

vitaly-t


People also ask

How do you conditionally add property to an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

Can a property of an object be an array?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.


2 Answers

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 }]
like image 52
Ivan Nosov Avatar answered Sep 28 '22 08:09

Ivan Nosov


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' }
]
like image 27
Khalid Avatar answered Sep 28 '22 06:09

Khalid