excluding from an object angular ng-change - angularjs

Hello guys i am trying to clear my ng-model when i fire my change function but my problem that i don't want to delete all i want to exclude one item in the object.
function change() {
if (vm.location.type) {
angular.forEach(vm.location, function (value, index) {
delete vm.location;
});
}
}
so i don't want to delete the
vm.location.type
my
vm.location
has
vm.location.boundaries;
vm.location.region;
vm.location.address;
vm.location.name;
vm.location.nonVisitingRadius;
vm.location.visitingRadius;

See the code below,
var obj = { a:123, b:123, c:123 }
delete obj.a;
Hence obj will be like this {b:123, c:123}
Note: Dont need any for loop to delete property from object
Updated Answer:
var obj= {
a: 'aaa',
b: 'bbb',
c: 'ccc',
d: 'ddd'
};
var removeObj = function(obj, props) {
for(var i = 0; i < props.length; i++) {
if(obj.hasOwnProperty(props[i])) {
delete obj[props[i]];
}
}
};
removeObj (obj, ["a", "d"]);

i don't know if i understand correctly what you're asking, but if you want to clear all the fields of your object preserving only type and preserving the reference of the object with plain javascirpt (no libraries), loop over the fields and check if the i field is equal to type.
for(var i in model.location){
if(i !== 'type')
delete model[i];
}
with underscore.js you could define a default model like:
var defaultModel = {
location: {
region: '',
address: '',
name: '',
nonVisitingRadius: '',
visitingRadius: '',
type: 'defaultvalue'
}
}
and when ng-change is triggered inside the function
_.extend(model, defaultModel);
that will keep the default value for type and clear all the others.

You can do it this with a temporary object :
let tempLocation = {};
tempLocation.type = $scope.location.type;
$scope.location = tempLocation;

Related

ANGULAR Components array key in result get value by id

this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.

react filtering an object of arrays

I'm trying to find a better way to remove value pairs of an object that contain an empty string ""
my current state is:
this.state = {
searchParams:{
query: '',
colors: [],
text: '',
legalities: '',
setName: '',
pageSize: 4
}
}
I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now
var search = this.state.searchParams.filter(function (el) {
return el !== "";
});
could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?
filter only use for a array, not is a object.
You can try my code
let searchParams =
Object.keys(this.state.searchParams)
.filter( key => this.state.searchParams[key] !== '' );
this.setState({searchParams })
You can use Object.entries and Object.fromEntries.
const filteredObject = Object.fromEntries(
Object.entries(searchParams)
.filter(([key, value]) => value !== "")
);
Will create anew object with all the keys for which the value was "" removed.
You can filter it this way with reduce method. Since it is an object, you have to combine object prototype .keys with array prototype .reduce to filter it.
const searchParams = {
query: '',
colors: [],
text: '',
legalities: '',
setName: '',
pageSize: 4
}
const notEmpty = Object.keys(searchParams).reduce((nonEmptyObj, currentKey) => {
if (searchParams[currentKey] !== '') {
nonEmptyObj[currentKey] = searchParams[currentKey];
}
return nonEmptyObj;
}, {})
console.log(notEmpty);
use Object.keys. In your case like this:
var search = Object.keys(this.state.searchParams).filter(el => {
// do something
})
the most simple way is by using Object.keys method and then iterate the whole object. then check if searchParams[ele] is true and add in another object.
var newObj = {};
Object.keys(this.state.searchParams).forEach(ele => {
if (searchParams[ele]) {
newObj = { ...newObj, [ele]: searchParams[ele] };
}
});
console.log(newObj); // new object generated with empty values eliminated
this.setState({searchParams:newObj})
If you want to filter out empty strings and strings (with white spaces only) as well, then
we have trim the string and then check its length. If its string and its length is 0 after trimming, then its considered as empty and will be filtered out.
const params = this.state.searchParams
Object.keys(this.state.searchParams).filter(key =>
!(typeof params[key] === 'string' && params[key].trim().length === 0)
)
If you don't want to trim, then:
const params = this.state.searchParams
Object.keys(this.state.searchParams).filter(key => params[key] !== '')
I would highly suggest you to not to use semicolon, as it takes space and JS can now ignore semicolon as well. Also, not to use double quotes unless required.

Ember array serialization

I'm adding objects to an array property of a model, then saving it. When I look at the outgoing request, the property in question is always an empty array.
My custom serializer (extending Ember.RESTSerializer) has this:
DS.ArrayTransform = DS.Transform.extend(
{
deserialize: function(serialized)
{
return (Ember.typeOf(serialized) == "array") ? serialized : [];
},
serialize: function(deserialized)
{
var type = Ember.typeOf(deserialized);
if (type == 'array')
{
return [{foo:'bar'}];
// return deserialized;
}
else if (type == 'string')
{
return deserialized.split(',').map(function(item)
{
return item.trim();
});
}
else
{
return [];
}
}
});
App.register("transform:array", DS.ArrayTransform);
As you can see I've tried passing back an arbitrary array with an object in it, but even then the array always comes out as empty. In the app I create the record like this:
var post = this.store.createRecord('explorePost', {
title: content.get('title'),
text: content.get('text'),
postDate: content.get('postdate'),
publishDate: content.get('publishDate'),
published: content.get('published'),
postType: content.get('postType'),
link: content.get('link,'),
projectDownloads: [],
// projectDownloads: this.model.get('projectDownloads'),
projectLinks: content.get('projectLinks'),
});
then add the objects like this:
this.model.get('projectDownloads').forEach(function (_download) {
console.log('pushing download', _download);
post.get('projectDownloads').pushObject(_download);
});
I can confirm that at time of saving, the post object has a projectDownloads array with one object in it. No matter what I do I can't seem to get it to spit out the contents when it saves. It's definitely going into the custom serializer, and detects it as an array, but you can see something else seems to be overriding it.
Can anyone tell me what I'm doing wrong? My model setup is below:
App.ExplorePost = DS.Model.extend(
{
title: DS.attr('string'),
text: DS.attr('string'),
link: DS.attr('string'),
postDate: DS.attr('momentdate'),
publishDate: DS.attr('momentdate'),
user: DS.belongsTo('user',{async:true}),
postType: DS.attr('string'),
activity: DS.belongsTo('activity',{ inverse: 'explorePost', async:true}),
comments: DS.hasMany('comment',{ inverse: 'explorePost', async: true }),
// projectDownloads: DS.hasMany('projectDownload',{ inverse: 'explorePost'}),
projectDownloads: DS.attr('array'),
// projectLinks: DS.hasMany('projectLink',{ inverse: 'explorePost'}),
projectLinks: DS.attr('string'),
published: DS.attr('boolean', {defaultValue: true}),
// tags: DS.hasMany('tag')
sortdate: function()
{
var datestr = Ember.isEmpty(this.get('postDate')) ? '' : moment(this.get('postDate')).format('YYYYMMDDHHmm');
var fn = (datestr + '____________').slice(0, 12);
return fn;
}.property('postDate')
});
There's no built in DS.attr('array') and a naive implementation would probably not know how to serialize ember-data objects found inside. Did you intend to leave that in there? If you swap it back to the relationships you've commented out and change projectDownloads to work with the promise:
this.model.get('projectDownloads').then(function(downloads) {
downloads.forEach(function(_download){
post.get('projectDownloads').pushObject(_download);
});
});
This should work jsut fine. I put together something nearly identical the other day. http://emberjs.jsbin.com/zolani/3/edit?html,css,js,output
if you array not contain complex object, like array of string, you can use DS.attr(), it will work.

How to get property name in firebase

I have this in firebase.
{
'users':
{
'random1':
{
'name': 'David'
}
},{
'random2':
{
'name': 'Dan'
}
}
}
How to list out random1 and random2 using angularFire.
What I want to do is to get random1 and random2 then pass it url for later remove.
Example
ref.child('users/' + therandomidhere);
$scope.remove = userRef.remove();
I'm not exactly sure what you're trying to do, but you can remove a property in an object by simply setting it to null. For example:
function MyController($scope, angularFire) {
angularFire(ref, $scope, "users", {}).then(function() {
// You can delete random1 by doing:
$scope.users["random1"] = null;
// Or:
delete $scope.users["random1"];
// You can enumerate all the keys by:
for (var key in $scope.users) {
console.log(key);
}
});
}
Hope this helps!

Check input value against an array

I am using this plugin for my autocomplete form:
http://www.planbox.com/blog/news/updates/jquery-autocomplete-plugin-for-backbone-js.html
Instead of checking only one item, as in the code below (if (inputVal == 'bakaxel')),
I would like to check the selected value against the entire collection
var collection = new Backbone.Collection([
{id:"AB", name:"Alberta"},
{id:"AD", name:"Album"},
{id:"BA", name:"barn"},
{id:"BC", name:"bak"},
{id:"BD", name:"baby"},
{id:"BE", name:"band"},
{id:"BF", name:"bakaxel"},
{id:"BG", name:"batteri"},
{id:"BH", name:"barbie"},
{id:"MB", name:"Manitoba"},
{id:"AP", name:"Armed Forces Pacific"}
]);
$('input.search').autocomplete({
collection: collection,
attr: 'name',
noCase: true,
ul_class: 'search_options tr_list',
ul_css: {'z-index':1234}
});
$('input.search').each(function(){
$(this).blur(function(){
var inputVal = $('input.search').val();
if (inputVal == 'bakaxel') {
$('#search_result_page').load('searchResult.html');
$('#searchPage').addClass('hidden');
}
});
});
I tried this, but I'd rather not create the ar array again, just use the backbone collection:
$('input.search').each(function(){
$(this).blur(function(){
var inputVal = $('input.search').val();
var ar = ["Alberta", "Album", "barn", "bak", "baby", "band", "bakaxel", "batteri", "barbie", "Manitoba", "Armed Forces Pacific"];
if (jQuery.inArray(inputVal, ar) != -1) {
$('#search_result_page').load('searchResult.html');
$('#searchPage').addClass('hidden');
}
});
});
Backbone proxies Underscore functions and most notably in your case http://underscorejs.org/#where
where _.where(list, properties)
Looks through each value in the list, returning an array of all the values that contain all of the
key-value pairs listed in properties.
Your test could be written as
var matches = collection.where({
name: inputVal
});
if (matches.length>0) {
...
}
Or as #mu suggested in the comments, you could just check the existence of the input with http://underscorejs.org/#find
var found = collection.find(function(model) {
return model.get('name') === inputVal
});
if (found) {
...
}

Resources