Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove $$hashKey from array

Tags:

angularjs

$scope.appdata = [{name: '', position: '', email: ''}];

This is the array which I created in angular controller.

Then I inserted some values in to array by using push method:

$scope.appdata.push({name: 'jenson raby', position: '2', email: '[email protected]'});

This is the array values after insertion:

$$hashKey:"00F",name:"jenson raby",position:"2",email:"[email protected]",

Here an extra $$hashKey has been added to the array after insertion, but I need to remove this from array.

like image 601
Jenson Raby Avatar asked Sep 02 '15 04:09

Jenson Raby


2 Answers

Based on your comment that you need to insert the array into the database, I'm going to assume that you are converting it a JSON string and then saving it to the DB. If that's incorrect, let me know and I'll see if I can revise this answer.

You have two options for modifying your array when converting it to JSON. The first is angular.toJson, which is a convenience method that automatically strips out any property names with a leading $$ prior to serializing the array (or object). You would use it like this:

var json = angular.toJson( $scope.appdata );

The other option, which you should use if you need more fine grained control, is the replacer argument to the built-in JSON.stringify function. The replacer function allows you to filter or alter properties before they get serialized to JSON. You'd use it like this to strip $$hashKey:

var json = JSON.stringify( $scope.appdata, function( key, value ) {
    if( key === "$$hashKey" ) {
        return undefined;
    }

    return value;
});
like image 107
Sean Walsh Avatar answered Nov 10 '22 14:11

Sean Walsh


Fast solution for lazy people :

JSON.parse(angular.toJson($scope.appdata))
like image 30
Yahia Mgarrech Avatar answered Nov 10 '22 16:11

Yahia Mgarrech