Iterating through object array in $scope and updating it - javascript

I have an array of objects in the scope ($scope.contracts). When I run my function, I pass in a contract. I Want it to iterate through $scope.contracts and find the one with the same .CONT_ORDNO. Then I want to set this contract to the contract passed in.
$scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
angular.forEach($scope.contracts, function (con) {
if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
con = $scope.contractToMerge;
}
});
};
Here is me trying to do it, it does everything I want except that only the con variable is changed, the actual contract that's an array location in $scope.contracts is not being updated. How do I make sure it is?
Note I don't want to remove and replace the contract, I want to update it.
Edit: I updated the if statement to have two (==). This doesn't fix it. It still is only setting the con variable correctly, not the $scope.contracts array location.

Assigning to con only changes the local variable. Try this instead:
$scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
angular.forEach($scope.contracts, function (con, i) {
if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
$scope.contracts[i] = $scope.contractToMerge;
}
});
};
Also, you need to change = to == in the if statement.

need == in the if condition
if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {

Related

Filter an Array of Objects from an Array in TypeScript

I built a custom component that filters an array of objects. The filter uses buttons, sets from active to non-active and allows more than one option on/off at the same time.
StackBlitz of my attempt - https://stackblitz.com/edit/timeline-angular-7-ut6fxu
In my demo you will see 3 buttons/options of north, south and east. By clicking on one you make it active and the result should include or exclude a matching "location" either north, south and east.
I have created my methods and structure to do the filtering, I'm struggling with the final piece of logic.
So far I have created a method to create an array of filtered locations depending on what the user clicks from the 3 buttons.
Next this passes to my "filter array" that gets the logic that should compare this filtered array against the original to bring back the array of results that are still remaining.
Its not quite working and not sure why - I originally got this piece of functionality working by using a pipe, but fore reasons do not want to go in that direction.
//the action
toggle(location) {
let indexLocation = this.filteredLocations.indexOf(location);
if (indexLocation >= 0) {
this.filteredLocations = this.filteredLocations.filter(
i => i !== location
);
} else {
this.filteredLocations.push({ location });
}
this.filterTimeLine();
}
// the filter
filterTimeLine() {
this.filteredTimeline = this.timeLine.filter(x =>
this.contactMethodFilter(x)
);
}
//the logic
private contactMethodFilter(entry) {
const myArrayFiltered = this.timeLine.filter(el => {
return this.filteredLocations.some(f => {
return f.location === el.location;
});
});
}
https://stackblitz.com/edit/timeline-angular-7-ut6fxu
Sorry for my expression but u have a disaster in your code. jajaja!. maybe u lost that what u need but the logic in your functions in so wrong. comparing string with objects. filter a array that filter the same array inside... soo u need make a few changes.
One:
this.filteredLocations.push({location});
Your are pushing object. u need push only the string.
this.filteredLocations.push(location);
Two:
filterTimeLine() {
this.filteredTimeline = this.timeLine.filter(x =>
this.contactMethodFilter(x)
);
}
in this function you filter the timeLine array. and inside of contactMethodFilter you call filter method to timeLine again....
See a functional solution:
https://stackblitz.com/edit/timeline-angular-7-rg7k3j
private contactMethodFilter(entry) {
const myArrayFiltered = this.timeLine.filter(el => {
return this.filteredLocations.some(f => {
return f.location === el.location;
});
});
}
This function is not returning any value and is passed to the .filter
Consider returning a boolean based on your logic. Currently the filter gets undefined(falsy) and everything would be filtered out

Data not updating in Vuejs

Let me start by explaining my use case, I have a fee_map attr on data which is a list of objects which contain data about the fee student has to pay, balance, payment mode etc, and a computed property, lets say 'updateOptions' which returns a list of objects with id and text suitable to populate select2(payment mode), now whenever user does something, updateOptions will be called. and on some other user actions Program will choose the selected option and set it on fee_map, structure for fee_map is as below.
data: {
fee_map: {
1: {
details:{
1: {
option_selected: "1",
}
}
// other_attr
},
2: {
details:{
1: {
option_selected: "2",
}
}
// other_attr
},
}
I have a method UpdateSelected, which will update the selections, where I loop through the fee_map by fetching keys and looping with forEach. and then set the selected option as below
var fee_map = this.fee_map;
t_keys = Object.keys(fee_map);
t_keys.forEach(function(t){
f_keys = Object.keys(fee_map[t].details);
f_keys.forEach(function(f){
fee_map[t].details[f].option_selected = "2";
});
});
Now, when I update the option_selected from here, my fee_map is not updated with new value. What am I doing wrong here?
Your object of objects is one level deeper than you were iterating over. So when you have fee_map[t].details[f], f is the key "details"and details["details"] is undefined. You need to do a foreach for the details object as well as can be seen here.
https://jsfiddle.net/50wL7mdz/78427/
var fee_map = this.fee_map;
t_keys = Object.keys(fee_map);
t_keys.forEach(function(t){
f_keys = Object.keys(fee_map[t]);
f_keys.forEach(function(f){
d_keys = Object.keys(fee_map[t][f]);
d_keys.forEach(function(d){
fee_map[t].details[d].option_selected = "5";
});
});
});
After lot of struggle I found code is updating data too quickly in a loop, but somehow vue is detecting changes only on the next tick, so I had to call a self invoking function as a wrapper to Vue.nextTick to preserve the context and update the selected_option inside the Vue.nextTick callback and that is working perfect.
working code below
(function(fee, ref){
console.log("Registering vue tick");
Vue.nextTick(function(){
console.log("Vue ticked, updating selected option");
fee.option_selected = ref;
});
})(fee, ref);

Function to conditionally assign variable member data to nested array in object?

I want to add data into an object, and my object contains nested data. Example data:
pageviewEvent {
client: "clientName",
page {
document_referrer: 'some http refer header data goes here',
window_height: 1920,
window_width: 1200
}
}
Some data is undefined or null and I do not want to add this undefined/null data into the object.
I made a function that works to add data to the object conditionally (if not undefined) but I can't figure out how to add data to nested objects in the function?
I could just make a bunch of if statements, but figure it's better to put the condition test into a function to reduce code size.
Example code with comment showing thinking of what I am trying but doesn't work:
//function to check if variable undefined or null, if not -> add to pageviewEvent arrayKey, variableName
function isUndefinedNull(arrayKey, variableName) {
var evalVariableName = eval(variableName);
if (evalVariableName !== undefined && evalVariableName !== null && evalVariableName !== "") {
console.log(arrayKey);
console.log(variableName);
pageviewEvent[arrayKey] = evalVariableName;
//array key could be nested, for instance pageview[page][title] or pageview.page.tile
}
}
//make event array
const pageviewEvent = { }
//add static data
pageviewEvent.client = 'neguse';
//if not null or undefined add data
isUndefinedNull('referrer.full', 'document.referrer');
//want to put data into object pageviewEvent.referrer.full or pageviewEvent[referrer][full]
Thanks for any help. I feel like this answer can help but I can't figure it out.
I recommend using the lodash function _.set(), documentation can be found here: https://lodash.com/docs/4.17.4#set
_.set( pageviewEvent, "referrer.full", "some-value" );
If you want to customise the behaviour of how nesting is handled when there's an undefined value, you can instead use _.setWith() - see https://lodash.com/docs/4.17.4#setWith

Using Filter Function to Find Values Equal to False and Setting to True

In my Angular app I have a function that drills down to an array, and then uses a filter function to pull out values in a new array where "completed" is "false".
This is working as expected. And the way our data is, there is always one object in the array that has the property for "completed" set to "false", so I can target [0] to get to that. So, from there all I need to do is set it to "true". However, for whatever reason, how to accomplish this last step is eluding me.
This is my whole function, and what I've tried thus far:
private completeLastWorkflowStatus() {
let currentService = this.checkDiscipline();
for (let service of this.client.services) {
if (service.service === currentService) {
let targetWorkflow = service.workflow;
let inCompleteWorkflow = targetWorkflow.filter(workflow => workflow.completed === false);
console.log(inCompleteWorkflow);
if (inCompleteWorkflow[0].completed === false) {
inCompleteWorkflow[0].completed === true;
console.log(inCompleteWorkflow[0].completed);
}
}
}
}
For the last console.log listed above, I still get "false" as the value. What am I missing here? How can I set the value of "completed" to "true" for this one object in the array?
inCompleteWorkflow[0].completed === true; is not assignment. Do inCompleteWorkflow[0].completed = true;

Javascript ERROR, undefined, not an object

I am new in JavaScript, And I am trying to map my controller's buttons and leds for mixxx application. Is that an object, an array? var is missing.
BehringerCMDMM1.leds = [
// Master
{ "shiftButton" : 0x12 },
// Deck 1
{ "sync" : 0x30 },
// Deck 2
{ "sync" : 0x33 }
];
I have an error here,
BehringerCMDMM1.shiftButton = function (channel, control, value, status, group) {
// Note that there is no 'if (value)' here so this executes both when the shift button is pressed and when it is released.
// Therefore, BehringerCMDMM1.shift will only be true while the shift button is held down
var deck = BehringerCMDMM1.groupToDeck(group);
BehringerCMDMM1.shift = !BehringerCMDMM1.shift // '!' inverts the value of a boolean (true/false) variable
BehringerCMDMM1.setLED(BehringerCMDMM1.leds[deck]["shiftButton"], BehringerCMDMM1.shift);
}
about "shiftButton" as undefined.
also I have this function
BehringerCMDMM1.setLED = function(value, status) {
status = status ? 0x7F : 0x00;
midi.sendShortMsg(0x94, value, status);
}
This is from a javascript file I found on the internet created for a different controller. So, I am trying things to understand how can I configure mine.
BehringerCMDMM1.leds is an array of objects. Within that array, the element at index 0 is an object that has a shiftButton property. Thus, the only way to get the 0x12 value in your example is to do this:
BehringerCMDMM1.leds[0]['shiftButton']
So when this code executes...
var deck = BehringerCMDMM1.groupToDeck(group);
...the value of deck is probably something other than 0, and you're accessing one of the sync objects in the BehringerCMDMM1.leds array. For example, if the value of deck was 1, then this...
BehringerCMDMM1.leds[deck]['shiftButton']
...will be undefined because you're effectively doing this:
BehringerCMDMM1.leds[1]['shiftButton']
Ok,
I am new in JavaScript, And I am trying to map my controller's buttons and leds for mixxx application. Is that an object, an array?
You have a array of objects.
var is missing.
You should test what is inside yout deck variable. Try this:
console.log(deck);
if (deck in BehringerCMDMM1.leds) {
BehringerCMDMM1.setLED(BehringerCMDMM1.leds[deck]["shiftButton"], BehringerCMDMM1.shift);
} else {
console.log("Index: "+deck+" doesn't exist");
}

Categories