How to reset object value to null in angularjs? - javascript

This is my code
var data={};
data={stdId:"101"};
data={empId:"102"};
data={deptId:"201"};
I have a data object getting data from services with one key only. but key names are different like stdId or empId ,etc.
I want to assign empty value to stdId or empId ,etc. like data={stdId:""} .
The key names are changed dynamically based on services.

Not entirely sure what you are trying to achieve, but if you know the name of the property you could use:
data['stdId'] = '';
or
data.stdId = '';
If you do not know the property name, but you still want to keep the property names on the object you could use:
for(var prop in data) {
if(data.hasOwnProperty(prop)) {
data[prop] = '';
}
}

You can use for..in loop to iterate over data object using key.
for(var key in data){
if(data.hasOwnProperty(key)){
data[key] = '';
}
}
Note: This will set every property of data object to ''

data.stdId = null;
or
data.stdId = '';
or
data = { stdId };
Have you tried those?

As I understand your question, you won't know the name of the key in each object and there is only ever one. To solve your problem:
data[Object.keys(data)[0]] = ''
This will assign the value of the key to null.

Related

unable to insert a new key value pair to the existing pair

We have name value pair field in our table.These field can be modified i.e either existing values can be changed or a new pair might get added .
We have written the below script to update existing values .
Please help on how to add ,new pair to the existing .
for (var name in u_service_characteristics) {
if (parsed.service_characteristics[name] != null &&
parsed.service_characteristics[name] != undefined) {
u_service_characteristics[name] = parsed.service_characteristics[name];
}
}
Above code only modifies the existing names ,how to insert if the incoming name doesnt exist.
I am guessing this is what you need
var existings = Object.getOwnPropertyNames(u_service_characteristics);
for (var name in parsed.service_characteristics) {
if (!existings.includes(name)) {
u_service_characteristics[name] = parsed.service_characteristics[name];
}
}
Instead of iterating over the keys of the target, just iterate over the keys of the source:
for(var name in parsed.service_characteristics)

Iterating over and comparing properties of two arrays of objects

I have set up a HBS helper which takes in two arrays of objects (users privileges). What I want to do is compare them and inject back into the template the privileges the user does and doesn't have.
Presently I can compare the names of the privileges with the following code:
hbs.registerHelper('selected', function(option, value){
var i;
var j;
var privName;
var userPriv;
var privObj = new Object();
var privArray = [];
for(i in option){
console.log('each ' + JSON.stringify(option[i]));
privName = option[i].privname;
for (y in value){
if(privName == value[y].privname){
userPriv = value[y].privname;
console.log('user has the following privileges', value[y].privname);
privObj = new Object();
privObj.name = userpriv;
privObj.id = value[y]._id;
privObj.state = 'selected';
privArray.push(privObj);
} else if (privName != value[y].privname){
console.log('user doesnt have priv ', privName);
privObj = new Object();
privObj.name = option[i].privname;
privObj.id = option[i].id;
privObj.state = '';
privArray.push(privObj);
}
}
}
console.log('privileges array ', privArray);
return privArray;
});
This works OK when the user only has one privilege, however when the user has more than one, for example two privileges, it returns the privileges twice. If the user has 3, thrice and so on. I know this is because the array is looping again because their are 2, 3 etc in the .length. However I can't seem to find an adequate solution.
Any help?
P.S. it would be nice if the Array.includes() method allowed you to search object properties.
The problem creating new objects the way you did is that for each property you add to your privilege-entity you will have to return to that function and set that property as well. You can instead just add/alter the state property of the existing objects:
hbs.registerHelper('selected', function(option, value) {
var names = option.map(function(opt) {
return opt.privname;
});
value.forEach(function(val) {
val.state = names.indexOf(val.privname) >= 0 ? 'selected' : '';
});
return value;
});
Basically:
The variable names is being mapped to be an array only with the privnames. You can check by using console.log(names).
The Array.forEach() function is helpful in this case because you just need to iterate over each object inside value and set its state-property.
To check if the privname exists, you just need to check the index in the previous names-mapped-array. For such a simple thing I used ternary operator (?:).
Finally, you return value, which is the array containing the objects you had updated.

How to handle multiple fieldnames and values as variables using mongoose "where" method?

I am using the where method to pass the fieldname and the value to a Mongoose fineOne query.
Model.findOne().where(field1,value1).where(field2, value2).exec(function(err,callback) {
...
}
The above works find. However, my problem is that we have more fieldnames and values to be passed to the above statement. I don't know exactly the number of fieldname and the value to be used since it depends on the user's configuration. I like to use a for loop to dynamically build the where clause, but don't know how. Can someone help?
Assuming a values object that contains the values of the fields you want to save, and a fields array that contains the name of the fields to save, you could do it like this:
var values = {p_last_name: 'Smith', p_first_name: 'John', ... };
var fields ['p_last_name', 'p_first_name'];
var query = Model.findOne();
for (var i=0; i<fields.length; ++i) {
var field = fields[i];
query.where(field, values[field]);
}
query.exec(callback);
You can create a variable for the conditions:
var conditions = {};
for (i = 1; i < 3; i++) {
conditions['field' + i] = 'value' + i;
}
The conditions object will look like this:
console.log(conditions);
Object {field1: "value1", field2: "value2"}
This for loop is of course just an example, you can use kind of loop to build the object. Then you can execute the findOne() query this way:
Model.findOne(conditions, function(err, item) {
// ...
});

How can I add a field to each row of an array with Javascript?

I have a javascript variable:
var x =
{"ab":"x",
"cd":"y",
"de":"z",
"answers":[
{"answerId":222,"answerUId":1,"text":"x"},
{"answerId":223,"answerUId":2,"text":"A"},
{"answerId":224,"answerUId":3,"text":"A"}
]
}
How can I add a field to each element of the answers array called response with a value of null ?
You can add the new property to the objects, like this
x["answers"].forEach(function(currentObject) {
currentObject["response"] = null;
});
This iterates through each and every object and adds the response property to each of them.
Plain javascript:
for (key in x['answers']) {
x['answers'][key]['response'] = null;
}

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

Categories

Resources