简体   繁体   中英

How to remove functions from object javascript

In my app, I'm using angular.js .

I need to send (through PUT request) an object with 3 properties, like this:

var item = {
  a: 1,
  b: 2,
  c: 3
}

But when I do console.log(item) , it shows a lot of information I don't need, such as $delete , $get , and so on. Like this:

 {  
   ...
   $delete: function (params, success, error),
   $get: function (params, success, error),
   ...
   a: 1,
   b: 2,
   c: 3
}

I think it's because is a javascript promise or something.
Is there any way to get only a , b and c ? Maybe with lodash?


My Solution:

I used lodash like this:

 var valuesToPick = ['title', 'languageCode', 'jobTitle', 'location','economySegment', 'companyDescription' ...];

 var item = _.pick( vm.form, valuesToPick );

They are inherit from Object , not owned by item .

If you want to iterate over own properties, use a for ... in loop.

for (property in item) {
    item[property];
}

I used lodash _.pick like this:

 var valuesToPick = ['title', 'languageCode', 'jobTitle', 'location','economySegment', 'companyDescription' ...];

 var item = _.pick( vm.form, valuesToPick );

Items is now free of functions, just your info.

纯Javascript

var objectFunctionLess=JSON.parse(JSON.stringify(objectWithFunctions))

This is not a perfect solution but it should work:

Instead of:

submitFunction(object, function () {})

do the:

submitFunction(JSON.parse(angular.toJson(object)), function () {})

you can split it into:

var cleanObject = JSON.parse(angular.toJson(object))
submitFunction(cleanObject, function () {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM