admin管理员组

文章数量:1200771

I have the following object say,

{"id":"kl45wkfj1k4j34", "firstname":"Arun", "lastname":"K"}

and I have the key to be filtered, 'firstname, lastname' assigned in a string using comma separator.

How do I filter that object to get the output as follows:

{"firstname":"Arun", "lastname":"K"}

I have the following object say,

{"id":"kl45wkfj1k4j34", "firstname":"Arun", "lastname":"K"}

and I have the key to be filtered, 'firstname, lastname' assigned in a string using comma separator.

How do I filter that object to get the output as follows:

{"firstname":"Arun", "lastname":"K"}
Share Improve this question edited Feb 27, 2016 at 8:22 Arun Selva Kumar asked Feb 27, 2016 at 8:15 Arun Selva KumarArun Selva Kumar 2,7323 gold badges22 silver badges30 bronze badges 2
  • That object has an invalid key and value. – Jai Commented Feb 27, 2016 at 8:19
  • corrected the key value pair – Arun Selva Kumar Commented Feb 27, 2016 at 8:23
Add a comment  | 

10 Answers 10

Reset to default 7

Underscore's pick method is what you're looking for.

var obj = { "id": 'kl45wkfj1k4j34', "firstname": "Arun", "lastname": "K" };
var filter = 'firstname, lastname',
var result = _.pick(obj, filter.split(', '));

There are a lot of ways one could go about this. The answers so far assume you want to modify the existing objects but the question doesn't specify; the word "filter" suggests maybe not. So if you want to create a new filtered object, rather than mutate the existing one(s), you might employ a reduce function. You said your key list is a string, but for the sake of keeping the examples clean, let's assume you just do str.split(',') or similar so it's already an array before passing it to these functions.

ES5

function createObjectFilter(keys) {
  return function(obj) {
    return keys.reduce(function(acc, key) {
      acc[key] = obj[key];
      return acc;
    }, {});
  };
}

var myFilter = createObjectFilter([ 'a', 'b' ]);

var filteredObject = myFilter(object);

ES6

const createObjectFilter = keys => obj => keys.reduce((acc, key) => {
  acc[key] = obj[key];
  return acc;
}, {});

const myFilter = createObjectFilter([ 'a', 'b' ]);

const filteredObject = myFilter(object);

Now, the createObjectFilter function returns the actual filter function based on a given list of keys. You could make it "all in one", instead, but the advantage of this approach is that it becomes possible to reuse your filters in more situations. For example:

const filteredObjects = unfilteredObjects.map(myFilter);

Object.fromEntries comes in handy ba using an array of key/value pairs.

To prepare this, you copuld split the string and map the pairs first.

const
    object = { id: 'kl45wkfj1k4j34', firstname: "Arun", lastname: "K" },
    filter = 'firstname, lastname',
    keys = filter.split(', ');
    result = Object.fromEntries(keys.map(k => [k, object[k]]));

console.log(result);

var toBeFilteredObject = {...}; // {"id":"kl45wkfj1k4j34", "firstname":"Arun", "lastname":"K"}
var filteredObject = {};
'comma, seperated, string'.split(',').forEach(function(key) {
  key = key.trim();
  filteredObject[key] = toBeFilteredObject[key];
});

Using _.reduce

var data = {"id":"kl45wkfj1k4j34", "firstname":"Arun", "lastname":"K"}
var filters = 'firstname, lastname'.split(', ');
_.reduce(data,function(result,value,key){
 if(filters.indexOf(key)!=-1){
   result[key] =value
 }
 return result;
},{})

If you have this object:

 var obj = {"id":"kl45wkfj1k4j34", "firstname":"Arun", "lastname":"K"};  

Then you can do this:

delete obj.id;
console.log(obj);

Now as per comment:

var newlist = listarray.map(function (obj){
      delete obj.id;
       return obj;
});

This will create a new list array with no id.


Or with specific keys:

var newlist = listarray.map(function (obj){
       var o = {};
        o.firstname = obj.firstname;
        o.lastname = obj.lastname;
       return o;
});

More generic solution if you have the array

var obj = [{ "id": 'kl45wkfj1k4j34', "firstname": "Arun", "lastname": "K" }, { "id": '34234', "firstname": "kajshd", "lastname": "ajsdh" }, { "id": '263742', "firstname": "asdjasd", "lastname": "asdjahs" }],
    filter = 'firstname, lastname'.split(', '),
    result = {}; 
var output = [];
obj.forEach(function(i, j) {
  filter.forEach(function (k) {
    // console.log(obj[j]);
    result[k] = obj[j][k];
  }); 
  output.push(result); 
  result = {};
});

I've adapted the solution from @Nina to TypeScript, adding an improvement to it.

/**
 * Constructs a new object by picking certain properties of the given object.
 * Example: `const publicUser = pick(user, ['id', 'name'])`.
 * Adapted from https://stackoverflow.com/a/35667463/4034572.
 */
export function pick<T extends object, K extends keyof T>(
  object: T,
  keys: K[]
): Pick<T, K> {
  const entries = keys.filter((k) => k in object).map((k) => [k, object[k]])
  return Object.fromEntries(entries)
}

Usage example:

type User = {
  readonly id: number
  name: string
  email: string
  password: string
}

type PublicUser = Pick<User, 'id' | 'name'>

const user: User = {
  id: 2,
  name: 'Albert',
  email: '[email protected]',
  password: 'pwd',
}

const publicUser: PublicUser = pick(user, ['id', 'name'])
// publicUser is { id: 2, name: 'Albert' }

The nice thing is that TypeScript will not allow you to use an invalid key. For example, doing pick(user, ['xyz']) raises the error TS2322: Type '"xyz"' is not assignable to type 'keyof User'.

And you'll get autocomplete too :)

Improvement

I've added filter((k) => k in object) because without it doing pick(user, ['xyz']) would give { xyz: undefined }, adding a property that doesn't exist on type User.

However, with the filter it correctly gives {}, which is what makes sense since the property xyz does not exist on User.

const form = { some: "one", prop: "two", value: "three", foo: "f", bar: "b"},
hasFilled = Object.values(
    Object.fromEntries(
      "some, prop, value".split(", ").map((k) => [k, form[k]]),
    ),
  ).every((i) => i !== "");

with checking if has value on filtered property

If you are having array of objects then use this

 data = [{
   "id": "kl45wkfj1k4j34",
   "firstname": "Arun1",
   "lastname": "K1"
 }, {
   "id": "kl45wkfj1k4j14",
   "firstname": "Arun2",
   "lastname": "K2"
 }, {
   "id": "2",
   "firstname": "Arun3",
   "lastname": "K3"
 }];

 data = data.map(function(o) {
   delete o.id;
   return o
 })

 document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

本文标签: underscorejsHow to select properties from an object in JavascriptStack Overflow