i am getting below example data in this.selectedParameterContext.
Please try the below code.
deleteAllContextData(data) {
const newSelectedParameterContext = {
'records': []
};
this.selectedParameterContext.records.forEach(function (record) {
const newSelectedParameterValues = [];
record.values.forEach(function (parameter, parameterIndex) {
const isValid = data.data.values.find(function (item) {
return parameter.value === item.value && parameter.label === item.label;
});
if (isValid) {
newSelectedParameterValues.push(parameter);
}
});
newSelectedParameterContext.records.push({ ...record, 'values': newSelectedParameterValues });
});
this.selectedParameterContext = newSelectedParameterContext;
}
Related
I'm new to vue and I'm trying to make this work. I get some data from a XML, everything works, but I want to change which value I get from XML using a computed which gets a value from Store.
My computed is:
currentStep: {
set (val) {
this.$store.commit('setCurrentStep', val)
},
get () {
return this.$store.state.currentStep
}
}
With axios and xml2js I get all data with this Method:
getData() {
axios.get("https://something.xml").then((response) => {
this.parseXML(response.data).then((data) => {
this.flightInformations = data
})
})
},
parseXML(data) {
return new Promise((resolve) => {
let parser = new xml2js.Parser({
trim: true,
explicitArray: true,
});
parser.parseString(data, function (err, result) {
let obj = null
obj = result.flugplan.abflug[0].flug;
let flight_dates = {};
for (let item of obj) {
let flight_date = item.datum.join().toString();
if (!flight_dates[flight_date]) {
flight_dates[flight_date] = [];
}
flight_dates[flight_date].push({
flightNr: item.flugnr.join().toString(),
flightPlace: item.ort.join().toString(),
flightPlan: item.plan.join().toString(),
flightExpected: item.erwartet.join().toString(),
flightDate: item.datum.join().toString(),
})
}
resolve(flight_dates);
})
})
}
I need to change my OBJ using my computed like:
let obj = null
if (this.currentStep === 'departures') {
obj = result.flugplan.abflug[0].flug;
} else {
obj = result.flugplan.ankunft[0].flug;
}
But it does not work. Can you guys please help ?
Thank you very much.
Computed can only return some value instead of modifying anything.
Try this one:
computed: {
someData() {
return this.currentStep === 'departures' ? result.flugplan.abflug[0].flug : result.flugplan.ankunft[0].flug;
}
}
After that use a someData value:
const obj = this.someData
I get it finally and now works! here is the code, if someone have the same issue
getData() {
axios.get("something.xml").then((response) => {
this.parseXML(response.data).then((data) => {
this.flightInformations = data
})
.catch(err => {
console.log(`${err} data is not avaiable`)
})
})
},
parseXML(data) {
return new Promise((resolve) => {
let parser = new xml2js.Parser({
trim: true,
explicitArray: true,
});
parser.parseString(data, (err, result) => {
let obj = null
if (this.$store.state.currentStep === 'abflug') {
obj = result.flugplan.abflug[0].flug
} else {
obj = result.flugplan.ankunft[0].flug
}
let flight_dates = {};
for (let item of obj) {
let flight_date = item.datum.join().toString();
if (!flight_dates[flight_date]) {
flight_dates[flight_date] = [];
}
flight_dates[flight_date].push({
flightNr: item.flugnr.join().toString(),
flightPlace: item.ort.join().toString(),
flightPlan: item.plan.join().toString(),
flightExpected: item.erwartet.join().toString(),
flightDate: item.datum.join().toString()
})
}
resolve(flight_dates)
})
})
}
Now using Store, when I change my CurrentStep, it also changes which part of XML it reads.
i want to know how i can get a value/numbers through key/username ?
look like that console.log(acc.${username})
my js
...
app.get("/account", (req, res) => {
loggedIn = req.cookies.loggedIn;
username = req.cookies.username;
if (loggedIn == "true") {
db.list().then(keys => {
if (keys.includes(username)) {
res.render("settings.html", { username: username })
var data = fs.readFileSync('2FA.json');
var acc = JSON.parse(data)
//////////////////////////////////////////////
console.log(acc.${username}) // i want to see a numbers in user name look like in here
/////////////////////////////////////////////
} else {
res.redirect("/logout");
}
});
} else {
res.render("notloggedin.html");
}
});
my json
[
{
"youssefnageeb": 927342
},
{
"youssefnageeb1":310686
},
{
"youssefnageeb2": 105380
},
{
"youssefnageeb3": 431816
},
{
"youssefnageeb4": 484728
}
]
I am guessing "data" is in the format mentioned above.
So, you can do
const index = data.findIndex(function isAccountRow(row) { return typeof row[username] === 'number'; })
if(index === -1) {
return res.redirect("/logout");
}
const row = data[index];
console.log(row[username]); // will be the number
I have a 2 function,
inside my runConfigComplianceDeviceOnClick I am calling the getDeviceRunningCompliance function to get some other data and based on both the results I have to return an object,
But What I am observing my data from the getDeviceRunningCompliance (Axios request to get data) function is not returned and it executes next lines,
but when I see in the console value is updated,
How to handle this case,
how to wait for the function to execute and then go next javascript? wanted to deal with asynchronous data then proceed further to the next lines...
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
let some = getDeviceRunningCompliance(selectedDevices);
console.log("getDeviceRunningCompliance some ", some)
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some)
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss)
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
};
const getDeviceRunningCompliance = (selectedDevices) => {
let self = this;
let deviceRunningComplaince = [];
selectedDevices.forEach((val, index) => {
let obj = {};
getComplianceDetails(val.id).then(data => {
const complianceDetailsData = data;
if (complianceDetailsData) {
// this.setState({
// complianceDetailsData: data
// });
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
deviceRunningComplaince.push(obj);
// return cardStatus;
}
});
// deviceRunningComplaince.push(obj);
});
return deviceRunningComplaince;
};
This is how I solved this issue. Please comment if we can do this better.
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
getDeviceRunningCompliance(selectedDevices).then(function(some) {
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some);
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss);
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
});
};
const getDeviceRunningCompliance = selectedDevices => {
let promiseData = selectedDevices.map((val, index) => {
return getComplianceDetails(val.id).then(data => {
let obj = {};
const complianceDetailsData = data;
if (complianceDetailsData) {
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
return obj;
}
});
});
return Promise.all(promiseData);
};
I'm creating a series of filters and it's currently "ugly code that works". I'd like to output all of the filters from an array, but I can't figure out how to assign a variable to an element's dataset attribute. (You'll see that the code is the exact same for every filter except for what they're filtering).
Can anyone help show me how I could achieve this?
function filterList() {
const itemsNode = document.querySelectorAll(".js-filterable");
const items = Array.from(itemsNode);
const filterBrand = document.querySelector(".js-filter-brand");
const filterState = document.querySelector(".js-filter-state");
const filterCity = document.querySelector(".js-filter-city");
const filterOwner = document.querySelector(".js-filter-owner");
const filtered = document.querySelector(".js-filtered");
let filterValue;
let results;
// Listen for filter changes
if (filterBrand) {
filterBrand.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.brand === filterValue);
outputResults(results);
}
});
}
if (filterState) {
filterState.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.state === filterValue);
outputResults(results);
}
});
}
if (filterCity) {
filterCity.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.city === filterValue);
outputResults(results);
}
});
}
if (filterOwner) {
filterOwner.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.owner === filterValue);
outputResults(results);
}
});
}
// Update filtered list
function outputResults(results) {
while (filtered.firstChild)
filtered.removeChild(filtered.firstChild);
results.forEach(function(result) {
filtered.appendChild(result);
});
}
}
It seems like you just want it to be DRYer:
function filterList() {
const itemsNode = document.querySelectorAll(".js-filterable");
const items = Array.from(itemsNode);
const filterClasses = ['brand', 'state', 'city', 'owner']
filterClasses.forEach(filterClass => {
const filtered = document.querySelector(`.js-filter-${filterClass}`);
if (filtered) {
filtered.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value; // <-- why overwrite the param?
let results;
if (filterValue === "all")
results = items;
else
results = items.filter(item => item.dataset[filterClass] === filterValue);
outputResults(results);
});
}
})
}
// Update filtered list
function outputResults(results) {
const filteredItems = document.querySelector(".js-filtered");
while (filteredItems.firstChild)
filteredItems.removeChild(filteredItems.firstChild);
results.forEach(result => filteredItems.appendChild(result));
}
In particular notice:
filterClasses = ['brand', 'state', 'city', 'owner'] is used to iterate over the known class names
with item.dataset[filterClass] a variable is used to set the data value
I imagine you could begin with something like this:
const passThru = (x) => true;
// Return a filter function using the given property name
const filterPropName = (propName, filterValue) => filterValue === "all" ?
passThru :
({dataset}) => dataset[propName] === filterValue;
// ...
function createListener (propName) {
return () => {
const filterValue = this.value;
const results = items.filter(filterPropName(propName, filterValue));
outputResults(results);
}
}
if (filterBrand) {
filterBrand.addEventListener("input", createListener("brand"));
}
if (filterState) {
filterState.addEventListener("input", createListener("state"));
}
// Etc.
I am trying to query a Firebase database. I have the following code, but it returns an empty list, when there is matching data.
loadData() {
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(item => {
item.memberId1 === this.me.uid;
});
return filtered;
});
// if me not in firelist then create new chat
if (this.me && this.me.uid) {
let chatFound: boolean = false;
console.log('this.firelist', this.firelist);
this.firelist.forEach(chatItems => {
console.log('chatItems', chatItems);
for (let i = 0; i < chatItems.length; i++) {
console.log('chatItems['+i+']', chatItems[i]);
let memberId1: string = chatItems[i].memberId1;
let memberId2: string = chatItems[i].memberId2;
if (memberId1 === this.me.uid || memberId2 === this.me.uid) {
chatFound = true;
break;
}
}
if (!chatFound) {
//this.createChat();
}
});
}
}
I think my problem is with the filter.
The following code creates a chat successfully:
createChat(img1: string, img2: string) {
this.af.database.list('/chat/').push({
memberId1: this.me.uid,
memberId2: this.you.uid,
img1: img1,
img2: img2,
displayName1: this.me.displayName,
displayName2: this.you.displayName,
lastMsg_text: 'todo',
timestamp: Date.now(),
negativtimestamp: -Date.now()
})
}
The following filter works:
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(
item => item.memberId1 === this.me.uid
);
return filtered;
});