Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return object with subset of its attributes

Tags:

javascript

I've got a flat JavaScript object like this:

{ 
  id: 3726492,
  kind: 'user',
  permalink: 'nicholas',
  username: 'Nicholas',
  ...
  a lot more attributes
}

I'd like to create a new object which only has a subset of the attributes of the original object.

Something like

var newObject = oldObject.fields(['id', 'username']);

newObject would be

{ 
  id: 3726492,
  username: 'Nicholas'
}

Is there already something like this?

like image 649
Hedge Avatar asked Nov 12 '15 10:11

Hedge


People also ask

How to get a subset of a JavaScript object properties?

To get the subset of properties of a JavaScript Object, we make use of destructuring and Property Shorthand. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Which method return all properties of an object?

getOwnPropertyNames() The Object. getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

What is the function that returns the name of an objects class?

className = class( obj ) returns the name of the class of obj .


1 Answers

Try this

function pick(data, keys) {
  var result = {};
  
  keys.forEach(function (key) {
    if (data.hasOwnProperty(key)) {
      result[key] = data[key];
    }
  });
  
  return result;
}

var data = { 
  id: 3726492,
  kind: 'user',
  permalink: 'nicholas',
  username: 'Nicholas'
}

var newData = pick(data, ['id', 'kind']);
console.log(newData);

In underscorejs or lodash there is method .pick

var data = { 
  id: 3726492,
  kind: 'user',
  permalink: 'nicholas',
  username: 'Nicholas',
};

var newObject = _.pick(data, 'id', 'username');
console.log(newObject);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
like image 59
Oleksandr T. Avatar answered Oct 02 '22 19:10

Oleksandr T.