How to replace the property of the object dynamically in angualrjs? - angularjs

var $scope.form = {
Name: "",
fields: []
}
angular.forEach($scope.form.fields, function (f) {
if (f.hasOwnProperty('order')) {
//code to replace the value of the property
} else {
//if order is not present push the new values to the $scope.form.fields.
}
});
I have a pop up their I am appending textboxes.When i append one text box,I am pushing the object to $scope.form.fields i.e.,Name,id,order..When i append the second textbox it is itering 2 times and getting 3 textboxes displayed. Its getting doubled for every new textbox.So I thought when $scope.form.fields contains order i should have a right to change the name of the textbox.If its not present i'l just push those new object into $scope.form.fields.Can anyone give a solution for it .

As I can see you're having an array ie fields and you need to push the new values when array doesn't already contain the same. You can use either indexOf or inArray functions of array. Try below snippet
angular.forEach($scope.form.fields, function (f, key) {
if (f.indexOf('order') >= 0) { // check whether array contains `order` or not
$scope.form.fields[key]['order'] = 'new value';
} else {
$scope.form.fields.push('new value');
}
});

Related

How to Write a conditional statement in postman based on a value in an array

Within each element in an array, there may or may not be a value that I need to grab. If the value is not in one element, I want to go to the next element to look for it. I'd like to know how to write the statement to do that in my Postman test. I already know how to get the values when they exist, but I want to go through each element until I find what I'm looking for to put in the variable.
I've googled how to write the code, but I'm new to this and I'm having trouble.
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("Date", jsonData.array[0].field[1]);
if (postman.setGlobalVariable("Date", jsonData.array[0].field[1]) === ???
else (postman.setGlobalVariable("Date", jsonData.array[1].field[1]);)
Hi, Here is a sample response (thanks!): You can see the first element does not have the value, "NeedTheseDates" that I need to grab, but the second element does.
"SampleArray": [
{
"Date": "2019-05-18T00:00:00.0000000-04:00",
"NeedTheseDates": [],
"Anything": "data",
"OnlyDate": "2019-06-03T00:00:00.0000000-04:00"
},
{
"Date": "2019-06-16T00:00:00.0000000-04:00",
"NeedTheseDates": [
"2019-07-02T00:00:00.0000000-04:00",
"2019-07-03T00:00:00.0000000-04:00",
"2019-07-04T00:00:00.0000000-04:00",
"2019-07-05T00:00:00.0000000-04:00",
"2019-07-06T00:00:00.0000000-04:00",
"2019-07-07T00:00:00.0000000-04:00",
"2019-07-08T00:00:00.0000000-04:00",
"2019-07-09T00:00:00.0000000-04:00",
"2019-07-10T00:00:00.0000000-04:00",
"2019-07-11T00:00:00.0000000-04:00",
"2019-07-12T00:00:00.0000000-04:00"
],
Not very sure about the problem statement. So trying all combinations
If there are only two cases where the value could be (index 0 or 1)
let someDate = jsonData.array[0].field[1] === '???' ?
jsonData.array[0].field[1] : jsonData.array[1].field[1];
postman.setGlobalVariable('Date', someDate);
If the length of array is dynamic but the date you are looking for in field is always at index 1
let someDate;
jsonData.array.forEach((element) => {
element.field[1] === '???' && (someDate = element.field[1]);
});
postman.setGlobalVariable('Date', someDate);
This will traverse all the items irrespective of whether it finds the correct element before. You can use some to stop that
let someDate;
jsonData.array.some((element) => {
if (element.field[1] === '???') {
someDate = element.field[1]);
return true; // this will stop the loop
}
});
postman.setGlobalVariable('Date', someDate);
If the length of array is dynamic and field is also dynamic
let someDate;
jsonData.array.some((element) => {
element.field.some((oneDate) => {
if (oneDate === '???') {
someDate = oneDate;
return true; // this will stop the inner loop
}
});
if (someDate) {
return true; // this will stop the outer loop
}
});
postman.setGlobalVariable('Date', someDate);

Doc with ObjectId Array - push value if exists, remove otherwise

I'm new to MongoDB and mongoose.
So my model holds many fields, amongst them is an Array of ObjectIDs
var modelSchema = new Schema({
//...
inner_array: [Schema.Types.ObjectId],
//...
});
What I'm trying to achieve with my query is:
Find a model by it's Id,
If the inner array contains a specific value remove it from the array.
If the value is not within the inner_array, push it
var target_id = // document id
var inner_object_id = // value to push
models.MyModel.findOne(
{_id: target_id},
function (err, model) {
// IN THIS SCOPE 'INNER_OBJECT_ID' IS UNDEFINED
// if model.inner_array contains 'inner_object_id', remove it
// otherwise, push 'inner_object_id' into model.inner_array
model.save();
res.json(model); // return modified document to client
}
);
I believe this can be written in a single findOneAndUpdate, but I can't figure out the syntax..
Thanks alot!
I believe you can achieve that using MongooseArray.pull and MongooseArray.addToSet
var target_id = // document id
var inner_object_id = // value to push
models.MyModel.findOne({
_id: target_id
}, function (err, model) {
if (model.inner_array.indexOf(inner_object_id) !== -1) {
model.inner_array.pull(inner_object_id);
} else {
model.inner_array.addToSet(inner_object_id);
}
model.save();
res.json(model); // return modified document to client
}

Check if a value is present in scope

I have a scope called $scope.activities. Inside that scope are multiple objects. Each object has a string called viewed with the value of check or uncheck. I would like to check if the value uncheck is present in the scope.
I've created this, but it doesn't seem to work.
if (activities.indexOf("uncheck") == -1) {
console.log ('uncheck found')
$scope.newActivities = 'newActivities';
} else {
console.log ('no uncheck found')
}
Because in activities I have two objects, one with the uncheck value, and a object without it.
[{"id":2,", "viewed":"check"}, {"id":3,", "viewed":"uncheck"}]
You've got to loop each object and check the property - you can use Array.some
var hasValue = activities.some(function(obj) { return obj.viewed == "unchecked" });
You have to loop over each object in the array and test if the property "viewed" equal to "unchek"
var activities = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"uncheck"}];
var activities2 = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"check"}];
var check = function(data){
var checked = false;
for(var i in data){
if(data[i].hasOwnProperty("viewed") && (data[i]["viewed"]=="uncheck") ){
checked = true ;
}
}
return checked;
} ;
console.log(check(activities));
console.log(check(activities2));

How to get index of array element in loop?

I have an loop Angular JS:
angular.forEach($scope.message, function (item) {
return (item.id_user == input.id_user) ? true : false;
});
How to get index of array element in loop for each item?
I tried:
angular.forEach($scope.message, function (item, $index) {});
Sorry for all the vitriol of the community. You're very close to your solution but are a bit confused by documentation. It's okay, let me help clarify!
In the documentation for angular.forEach you will see the following statement:
Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key, obj), where value is the value of an object property or an array element, key is the object property key or array element index and obj is the obj itself. Specifying a context for the function is optional.
And then the following example:
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
Essentially, the code is like this:
angular.forEach('name of list/array you want to loop through', 'callback function to be called for each element of the list')
The important part that you're missing is that the 'callback...' mentioned above can be handed 3 variables which you can then use in your callback. Your callback will be called for each element in the list. Here is some explanation of those 3 variables:
Value: The value of the i-th element/property in the list/array/object
Key: i - the index belonging to the current item in the array
Object: the the object itself (or array/list itself)
Here is an example i put together for you where I use the Key to create a new string showing the index of each letter in $scope.message. Hope this helped!
angular.forEach($scope.arrayname,function(item,index){
console.log(item,index)
})
There is a way.
var index = 0;
angular.forEach($scope.message, function (item) {
return (item.id_user == input.id_user) ? index : false;
index = index + 1;
});
Here it will return $scope.message index value if item.id_user == input.id_user else returns false. You can also assign $scope.message[index] to some other scope variable like this
var index = 0;
angular.forEach($scope.message, function (item) {
if(item.id_user == input.id_user){
$scope.message[index] = $scope.yourVariable;
}
index = index + 1;
});
var items = ['a','b','c','d','e','f']
angular.forEach(items,function(item,index){
console.log(item)
console.log(index)
}

Angularjs: Assigning Array within object

I am having an issue with losing data within an array when i try to assign it to a new array.
My object im using is as follows:
$scope.shops = [
{
name: "Kroger",
items: [ { itemName: "Chips"} ]
}
];
This is the code for the functions im using, it may be a callback issue? or something? Im losing the items info for the shop.
$scope.addItem = function(newItem, newShop){
var x = findShop(newShop);
x.items.push(newItem);
$scope.shops.push(x);
};
findShop = function(shopTag){
var old = angular.copy($scope.shops);
var tar = {
name: shopTag,
items: []
};
$scope.shops = [];
angular.forEach(old, function(shop, key){
if(shop.name === shopTag) {
tar.items = angular.copy(shop.items);
}
else {
$scope.shops.push(shop);
}
});
return tar;
};
the goal is to have the findShop function return a shop with the correct name, with empty items if there wasnt a shop previously, or with items full of the items if the shop was already created. then the addItem will push the item into the shop.items array and push the shop into the $scope
Any help is greatly appreciated!!!
You are right , it is this line which is causing the problem ,
tar.items = shop.items;
Try using it like this ,
tar.items = angular.copy(shop.items);
var old = $scope.shops; // old and $scope.shops point to the same place
..........
$scope.shops = []; // you assigned a new array that overrides the data
............
angular.forEach(old, function(shop, key){ // for each on an empty array????
If you dont want to point to the same reference use:
var copiedObject = angular.copy(objToCopy);
I guess the array is getting empty even before for loop.
Var old is reference to shops array, which you are making empty before foreach.. effectively making old empty...

Resources