I am trying to add a Quick Launch functionality to a this homepage project which would, with a key press, launch all the URLs with quickLaunch property set to true.
I have set the scene by adding a quickLaunch property to the CONFIG object like so:
const CONFIG = {
commands: [{
{
category: 'General',
name: 'Mail',
key: 'm',
url: 'https://gmail.com',
search: '/#search/text={}',
color: 'linear-gradient(135deg, #dd5145, #dd5145)',
icon: 'mail.png',
quickLaunch: true,
},
{
category: 'General',
name: 'Drive',
key: 'd',
url: 'https://drive.google.com',
search: '/drive/search?q={}',
color: 'linear-gradient(135deg, #FFD04B, #1EA362, #4688F3)',
icon: 'drive.png',
quickLaunch: false,
},
{
category: 'Tech',
name: 'GitHub',
key: 'g',
url: 'https://github.com',
search: '/search?q={}',
color: 'linear-gradient(135deg, #2b2b2b, #3b3b3b)',
icon: 'github.png',
quickLaunch: true,
},
...and so on
and then added a condition to launch all the websites with quickLaunch option enabled:
class QueryParser {
constructor(options) {
this._commands = options.commands;
this._searchDelimiter = options.searchDelimiter;
this._pathDelimiter = options.pathDelimiter;
this._protocolRegex = /^[a-zA-Z]+:\/\//i;
this._urlRegex = /^((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)$/i;
this.parse = this.parse.bind(this);
}
parse(query) {
const res = {
query: query,
split: null
};
if (this._urlRegex.test(query)) {
const hasProtocol = this._protocolRegex.test(query);
res.redirect = hasProtocol ? query : 'http://' + query;
} else {
const trimmed = query.trim();
const splitSearch = trimmed.split(this._searchDelimiter);
const splitPath = trimmed.split(this._pathDelimiter);
this._commands.some(({
category,
key,
name,
search,
url,
quickLaunch
}) => {
if (query === key) {
res.key = key;
res.isKey = true;
res.redirect = url;
return true;
}
if (splitSearch[0] === key && search) {
res.key = key;
res.isSearch = true;
res.split = this._searchDelimiter;
res.query = QueryParser._shiftAndTrim(splitSearch, res.split);
res.redirect = QueryParser._prepSearch(url, search, res.query);
return true;
}
if (splitPath[0] === key) {
res.key = key;
res.isPath = true;
res.split = this._pathDelimiter;
res.path = QueryParser._shiftAndTrim(splitPath, res.split);
res.redirect = QueryParser._prepPath(url, res.path);
return true;
}
if (key === '*') {
res.redirect = QueryParser._prepSearch(url, search, query);
}
/* ---> */ if (query === 'q!') {
for (let i = 0; i < this._commands.length; i++) {
if (this._commands[i].quickLaunch === true) {
window.open(this._commands[i].url);
}
}
return true;
}
});
}
res.color = QueryParser._getColorFromUrl(this._commands, res.redirect);
return res;
}
static _getColorFromUrl(commands, url) {
const domain = new URL(url).hostname;
return (
commands
.filter(c => new URL(c.url).hostname.includes(domain))
.map(c => c.color)[0] || null
);
}
static _prepPath(url, path) {
return QueryParser._stripUrlPath(url) + '/' + path;
}
static _prepSearch(url, searchPath, query) {
if (!searchPath) return url;
const baseUrl = QueryParser._stripUrlPath(url);
const urlQuery = encodeURIComponent(query);
searchPath = searchPath.replace('{}', urlQuery);
return baseUrl + searchPath;
}
static _shiftAndTrim(arr, delimiter) {
arr.shift();
return arr.join(delimiter).trim();
}
static _stripUrlPath(url) {
const parser = document.createElement('a');
parser.href = url;
return `${parser.protocol}//${parser.hostname}`;
}
}
I expected the marked condition (commented with "-->") to fire only once but it is doing the whole process four times all over. I logged the URLs it is trying to launch and it looks like this:
Am I missing an obvious core concept?
Seems like this._commands.some( runs through all your this._commands, and then you check if query is query === 'q!' and i guess thats always true, and if thats the case then you loop through this._commands again. giving you this._commands.length * this._commands.length amount of output.
Related
Say I have the following strings:
"files/photos/foo.png"
"files/videos/movie.mov"
and I want to convert them to the following object:
{
name: "files"
children: [{
name: "photos",
children: [{
name: "foo.png",
id: "files/photos/foo.png"
}]
},{
name: "videos",
children: [{
name: "movie.mov",
id: "files/videos/movie.mov"
}]
}]
}
What would be the best approach for doing so? I've tried writing some recursive functions, however admit that I'm struggling at the moment.
Here's a quick snippet with a possible solution. It uses nested loops, the outer splitting each path by the delimeter and pop()ing the file portion out of the array. The inner iterates the parts of the path and constructs the heirarchy by reasigning branch on each iteration. Finally the file portion of the path is added to the deepest branch.
const data = [
'files/photos/foo.png',
'files/photos/bar.png',
'files/videos/movie.mov',
'docs/photos/sd.jpg'
];
const tree = { root: {} }
for (const path of data) {
const parts = path.split('/');
const file = parts.pop();
let branch = tree, partPath = '';
for (const part of parts) {
partPath += `${part}/`;
if (partPath === `${part}/`) {
tree.root[partPath] = (tree[partPath] ??= { name: part, children: [] });
} else if (tree[partPath] === undefined) {
tree[partPath] = { name: part, children: [] };
branch.children.push(tree[partPath]);
}
branch = tree[partPath];
}
branch.children.push({ name: file, id: path });
}
const result = Object.values(tree.root)
console.log(JSON.stringify(result, null, 2))
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row::after { display: none !important; }
Or as a function.
function mergeAssets(assets) {
const tree = { root: {} }
for (const path of data) {
const parts = path.split('/');
const file = parts.pop();
let branch = tree, partPath = '';
for (const part of parts) {
partPath += `${part}/`;
if (partPath === `${part}/`) {
tree.root[partPath] = (tree[partPath] ??= { name: part, children: [] });
} else if (tree[partPath] === undefined) {
tree[partPath] = { name: part, children: [] };
branch.children.push(tree[partPath]);
}
branch = tree[partPath];
}
branch.children.push({ name: file, id: path });
}
return {
name: "assets",
children: Object.values(tree.root)
}
}
const data = [
'files/photos/foo.png',
'files/photos/bar.png',
'files/videos/movie.mov',
'docs/photos/sd.jpg'
];
const result = mergeAssets(data);
console.log(JSON.stringify(result, null, 2))
I was able to find a solution using a recursive function. If others have any tips on how to improve this, I'd love to hear.
function mergeObjects(parentArray,path,originalName){
if(originalName === undefined){
originalName = path;
}
const parts = path.split("/");
var nextPart = "";
parts.forEach((part, index) => index > 0 ? nextPart += (nextPart !== "" ? "/" : "") + part : null);
//does the parentArray contain a child with our name?
const indexOfChild = parentArray.findIndex(child => child.name === parts[0]);
if(indexOfChild === -1){
//this item does not exist
if(parts.length > 1){
var index = parentArray.push({
name: parts[0],
children : []
}) - 1;
mergeObjects(parentArray[index].children,nextPart,originalName);
}else{
parentArray.push({
name: parts[0],
id : originalName
});
}
}else{
//this item already exists
if(parts.length > 1){
mergeObjects(parentArray[indexOfChild].children,nextPart,originalName);
}
}
}
And the function is called with the following:
function mergeAssets(assets){
var obj = {
name: "assets",
children: []
};
assets.forEach(asset => mergeObjects(obj.children,asset));
return obj;
}
I have a config object. Using this config object, I populate required elements by appending a string to the key of this object.I need help updating values
const MEMBER_INITIAL_VALUE = {
type: '',
dateOfBirth_: '',
seekingCoverage_: true,
relationshipToPrimary: ''
};
const updateInitialValue = (type, relationshipToPrimary) => {
var newMemberObjValue = JSON.parse(JSON.stringify(MEMBER_INITIAL_VALUE));
let updateValue = Object.entries(newMemberObjValue).forEach(([key, value]) => {
[`${key}_${type}`]: value; //I'm stuck here. not sure how to proceed
delete key;
});
return updateValue;
};
updateInitialValue = ('applicant', 'SELF');
updateInitialValue = ('spouse', 'DEPENDANT');
Expected Result:
{
type: 'applicant',
dateOfBirth_applicant: '',
seekingCoverage_applicant: true
relationshipToPrimary: 'SELF'
};
{
type: 'spouse',
dateOfBirth_spouse: '',
seekingCoverage_spouse: true
relationshipToPrimary: 'DEPENDANT'
};
Since you're not updating the original object, you can simplify this greatly:
const MEMBER_INITIAL_VALUE = {
type: '',
dateOfBirth_: '',
seekingCoverage_: true,
relationshipToPrimary: ''
};
const updateInitialValue = (type, relationshipToPrimary) => ({
type,
relationshipToPrimary,
[`dateOfBirth_${type}`]: MEMBER_INITIAL_VALUE.dateOfBirth_,
[`seekingCoverage_${type}`]: MEMBER_INITIAL_VALUE.seekingCoverage_
});
let updatedValue = updateInitialValue('applicant', 'SELF');
updatedValue = updateInitialValue('spouse', 'DEPENDANT');
This should do the trick:
const MEMBER_INITIAL_VALUE = {
type: '',
dateOfBirth_: '',
seekingCoverage_: true,
relationshipToPrimary: ''
};
const updateInitialValue = (type, relationshipToPrimary) => {
let newMemberInitialValue = JSON.parse(JSON.stringify(MEMBER_INITIAL_VALUE));
Object.keys(newMemberInitialValue).forEach((key) => {
if(!['type', 'relationshipToPrimary'].includes(key)) {
newMemberInitialValue[`${key}_${type}`] = newMemberInitialValue[key];
delete newMemberInitialValue[key];
}
});
newMemberInitialValue.type = type;
newMemberInitialValue.relationshipToPrimary = relationshipToPrimary;
console.log(newMemberInitialValue);
};
let applicantValues = updateInitialValue('applicant', 'SELF');
let spouseValues = updateInitialValue('spouse', 'DEPENDANT');
EDIT: Missed returning the value from the function and then assigning to a new variable.
Although an answer was posted, because i also solved it and my solution is a bit different (though the other answer looks way too slimmer) i would post it here.
const MEMBER_INITIAL_VALUE = {
type: "",
dateOfBirth_: "",
seekingCoverage_: true,
relationshipToPrimary: "",
};
const updateInitialValue = (type, relationshipToPrimary) => {
var newMemberObjValue = JSON.parse(JSON.stringify(MEMBER_INITIAL_VALUE));
Object.entries(newMemberObjValue).forEach(([key, value]) => {
if (key === "type") {
newMemberObjValue[key] = type;
} else if (key === "dateOfBirth_") {
Object.defineProperty(
newMemberObjValue,
[`${key}_${type}`],
Object.getOwnPropertyDescriptor(newMemberObjValue, key)
);
delete newMemberObjValue[key];
newMemberObjValue[`${key}_${type}`] = value;
} else if (key === "seekingCoverage_") {
Object.defineProperty(
newMemberObjValue,
[`${key}_${type}`],
Object.getOwnPropertyDescriptor(newMemberObjValue, key)
);
delete newMemberObjValue[key];
newMemberObjValue[`${key}_${type}`] = value;
} else if (key === "relationshipToPrimary") {
newMemberObjValue[key] = relationshipToPrimary;
}
});
return newMemberObjValue;
};
const updatedValue1 = updateInitialValue("applicant", "SELF");
const updatedValue2 = updateInitialValue('spouse', 'DEPENDANT');
Though a few answers have already been posted, I would like to suggest a similar one that does the same thing in a much more clear and concise way:
function Member() {
this.type = '';
this.dateOfBirth = '';
this.seekingCoverage = true;
this.relationshipToPrimary = '';
}
function UpdateInitialValue(type, relationshipToPrimary) {
var newMember = new Member();
newMember.type = type;
newMember.relationshipToPrimary = relationshipToPrimary;
return newMember;
}
console.log(UpdateInitialValue('applicant', 'SELF'));
console.log(UpdateInitialValue('spouse', 'DEPENDANT'));
I have a JSON file from an external source containing a bunch of conditions I'd like to test. Either in realtime, or by somehow converting everything.
Let's say I have an instance of my class Person, containing {age: 13, country: "Norway"}, and that I have an external JSON file containing the following "helpers":
{
"is_child": "age < 16",
"is_adult": "age >= 16 and age < 67",
"is_senior": "age > 67",
"is_scandinavian": "country == 'Norway' or country == 'Sweden' or country == 'Denmark'",
}
and another file containing, for example, tickets I'd like to present, for example, "NorwegianTickets.json"
{
"childTicket": "is_child and is_scandinavian",
"flexTicket": "is_scandinavian and (is_adult or is_senior)"
}
How can I apply this logic to my code? If I want to run the condition "flexTicket" on my "Person", how should I map all the logic? How do I translate the "stringed" conditions, such as "and"/"or", and "()"?
You can easily achieve this using the eval function that execute a string as javascript.
So the logic will be:
Get the different conditions as a javascript string (is_child, is_adult, ...)
This function replace all variables (written as a string) by there value.
For that you will need to create a dictionary to list them all with the corresponding value:
const varsToReplace = {
country: 'Norway',
age: 12
}
Then you replace this variable in a given condition using the replace method. The only trick here is that you need to search for country and not country (if you not add the extra space before and after, a variable like user_country could be replaced by user_Norway). Also keep in mind that if you replace by a string you should wrapp the value in '':
const getConditionString = (condition) => {
let replacedConditon = ` ${conditions[condition]} `
Object.keys(varsToReplace).forEach((variable) => {
const re = new RegExp(` ${variable} `, 'g');
let replaceValue = ` ${varsToReplace[variable]} `
// If the value is a string we should add ''
if (typeof varsToReplace[variable] === 'string') {
replaceValue = ` '${varsToReplace[variable]}' `
}
replacedConditon = replacedConditon.replace(re, replaceValue)
})
return replacedConditon
}
Get the test as a javascript string (is_child and is_scandinavian, ...)
This function getTestString will replace all conditions key by the javascript string using the previous function:
const getTestString = (test) => {
let replacedTest = ` ${tests[test]} `
Object.keys(conditions).forEach((condition) => {
const re = new RegExp(` ${condition} `, 'g');
replacedTest = replacedTest.replace(re, ` ( ${getConditionString(condition)} ) `)
})
return replacedTest
}
Replace the different operators to be 'js valid':
const replaceOperators = (string) => {
const operators = {
or: '||',
and: '&&'
}
Object.keys(operators).forEach((operator) => {
const re = new RegExp(` ${operator} `, 'g');
string = string.replace(re, ` ${operators[operator]} `)
})
return string
}
Execute the js string using eval:
const evalTest = (test) => {
let testAsString = replaceOperators(getTestString(test))
return eval(testAsString)
}
Here is the full example:
const country = 'Norway'
const age = 12
const varsToReplace = {
country,
age
}
const conditions = {
"is_child": "age < 16",
"is_adult": "age >= 16 and age < 67",
"is_senior": "age > 67",
"is_scandinavian": "country == 'Norway' or country == 'Sweden' or country == 'Denmark'"
}
const tests = {
"childTicket": "is_child and is_scandinavian",
"flexTicket": "is_scandinavian and ( is_adult or is_senior )"
}
const getConditionString = (condition) => {
let replacedConditon = ` ${conditions[condition]} `
Object.keys(varsToReplace).forEach((variable) => {
const re = new RegExp(` ${variable} `, 'g');
let replaceValue = ` ${varsToReplace[variable]} `
// If the value is a string we should add ''
if (typeof varsToReplace[variable] === 'string') {
replaceValue = ` '${varsToReplace[variable]}' `
}
replacedConditon = replacedConditon.replace(re, replaceValue)
})
return replacedConditon
}
const getTestString = (test) => {
let replacedTest = ` ${tests[test]} `
Object.keys(conditions).forEach((condition) => {
const re = new RegExp(` ${condition} `, 'g');
replacedTest = replacedTest.replace(re, ` ( ${getConditionString(condition)} ) `)
})
return replacedTest
}
const replaceOperators = (string) => {
const operators = {
or: '||',
and: '&&'
}
Object.keys(operators).forEach((operator) => {
const re = new RegExp(` ${operator} `, 'g');
string = string.replace(re, ` ${operators[operator]} `)
})
return string
}
const evalTest = (test) => {
let testAsString = replaceOperators(getTestString(test))
console.log(testAsString)
return eval(testAsString)
}
console.log(evalTest('childTicket'))
console.log(evalTest('flexTicket'))
I would go for creating a DSL for that purpose. It's fun. I've written one to just give you some idea about it. Beware, its not fully tested, lacks basic functionality such as array access. I believe you may find better examples in the internet.
class Node_ {
children: Node_[];
constructor() {
this.children = [];
}
addChild = (node: Node_) =>
this.children.push(node);
evaluate = (context: any): boolean | number | string => {
throw new Error('Missing implementation');
}
}
enum ExprType {
Eq = 'eq',
Gt = 'gt',
Lt = 'lt',
Gte = 'gte',
Lte = 'lte',
Get = 'get',
}
class ExprNode extends Node_ {
expr: string;
constructor(expr: string) {
super();
this.throwIfInvalidExpr(expr);
this.expr = expr.toLowerCase();
}
throwIfInvalidExpr(expr: string) {
switch (expr.toLowerCase()) {
case ExprType.Eq:
case ExprType.Gt:
case ExprType.Lt:
case ExprType.Gte:
case ExprType.Lte:
case ExprType.Get:
break;
default:
throw new Error(`Unexpected expression: ${this.expr}`);
}
}
evaluate = (context: any) => {
switch (this.expr) {
case ExprType.Get:
return this.evaluateAccess(context);
default:
return this.evaluateCmp(context);
}
}
evaluateAccess = (context: any) => {
this.throwIfInvalidAccessOperands();
const prop = this.children[0].evaluate(context) as string;
const newContext = context[prop];
const child = this.children[1];
if (child) {
return child.evaluate(newContext);
} else {
return newContext;
}
}
evaluateCmp = (context: any) => {
this.throwIfInvalidOperands();
const left = this.children[0].evaluate(context);
const right = this.children[1].evaluate(context);
switch(this.expr) {
case ExprType.Eq:
return left === right;
case ExprType.Gt:
return left > right;
case ExprType.Gte:
return left >= right;
case ExprType.Lt:
return left < right;
case ExprType.Lte:
return left <= right;
}
}
throwIfInvalidOperands = () => {
if (this.children.length !== 2) {
throw new Error(`Invalid operand count ${this.children.length}`);
}
}
throwIfInvalidAccessOperands = () => {
if (this.children.length === 0 ||
this.children.length > 2) {
throw new Error(`Invalid access operand count ${this.children.length}`);
}
}
}
class ValueNode extends Node_ {
value: string | number;
constructor(value: string, str?: boolean) {
super();
if (str) {
this.value = value as string;
} else {
const num = parseInt(value);
if (Number.isNaN(num)) {
throw new Error(`Invalid number: ${value}`);
}
this.value = num;
}
}
evaluate = (_: any) => {
return this.value;
}
}
function tokenize(value: string): Node_ {
let index = 0;
const nodeStack = [];
let token = '';
while (index < value.length) {
switch(value[index]) {
case '(':
{
const node = new ExprNode(token);
nodeStack.push(node);
token = '';
}
break;
case ')':
{
if (token) {
const node = new ValueNode(token);
nodeStack.push(node);
addToParent(nodeStack);
token = '';
}
addToParent(nodeStack);
}
break;
case "'":
case '"':
const str = consumeString(value, index);
index += str.length + 1;
token += str;
{
const node = new ValueNode(token, true);
nodeStack.push(node);
addToParent(nodeStack);
}
token = '';
break;
case ',':
if (token) {
const node = new ValueNode(token);
nodeStack.push(node);
addToParent(nodeStack);
token = '';
}
break;
case ' ':
break
default:
token += value[index];
}
index++;
}
return nodeStack[0];
}
function consumeString(value: string, index: number) {
const delimiter = value[index++];
let ret = '';
while (value[index] !== delimiter) {
ret += value[index];
index++;
}
return ret;
}
function addToParent(nodeStack: Node_[]) {
console.assert(nodeStack.length > 0);
const last = nodeStack.pop();
if (nodeStack.length > 0) {
const parent = nodeStack.pop();
parent.addChild(last);
nodeStack.push(parent);
} else {
nodeStack.push(last);
}
}
{
const ast = tokenize('EQ("origami", GET("name"))');
const context = { name: 'origami' };
const context2 = { };
console.assert(ast.evaluate(context) === true);
console.assert(ast.evaluate(context2) === false);
}
{
const ast = tokenize('EQ(5, 5)');
console.assert(ast.evaluate({}) === true);
const ast1 = tokenize('EQ("foo", "foo")');
console.assert(ast1.evaluate({}) === true);
const ast2 = tokenize('EQ("foo", "bar")');
console.assert(ast2.evaluate({}) === false);
const ast3 = tokenize('GTE(15, 10)');
console.assert(ast3.evaluate({}) === true);
}
{
const ast = tokenize('GET("info", GET("person", GET("age")))');
const context = { info: { person: { age: 21 } } };
console.assert(ast.evaluate(context) === 21);
}
{
const ast = tokenize('LTE(21, GET("info", GET("person", GET("age"))))');
const context = { info: { person: { age: 21 } } };
console.assert(ast.evaluate(context) === true);
const context2 = { info: { person: { age: 15 } } };
console.assert(ast.evaluate(context2) === false);
}
{
const ast = tokenize('EQ(GET("info", GET("person", GET("planet"))), "earth")');
const context = { info: { person: { planet: "mars" } } };
console.assert(ast.evaluate(context) === false);
}
{
const ast = tokenize('GT(GET("person1", GET("age")), GET("person2", GET("age")))');
const context = { person1: { age: 56 }, person2: { age: 21 } };
console.assert(ast.evaluate(context) === true);
const context2 = { person1: { age: 25 }, person2: { age: 44 } };
console.assert(ast.evaluate(context2) === false);
}
I omitted AND & OR expressions, but it should be clear how to add them.
In this scenario, the client should submit the data along with the constraints. For example:
{
"context": {
"person": {
"age": 44,
"planet": "saturn"
}
},
"constraints": {
"shouldFrom": "EQ('mars', GET('person', GET('planet')))",
"minimumAge": "GTE(40, GET('person', GET('planet')))"
}
}
And the receiver part takes the each constraints, tokenize them and evaluate them with given context.
I have grid which I want to export:
initializeColumnDefs() {
this.columnDefs = [];
this.columnDefs.push({
headerName: 'time,
field: 'completedTimestamp',
cellRenderer: (params: any) => {
if (params.data.isMomentarily)
return '';
return DatagridComponent.DefaultDatetimeCellRenderer(params);
},
comparator: (valueA: number, valueB: number) => {
return DatagridComponent.DefaultDatetimeCellComparator(valueA, valueB);
}
},
{
headerName: 'people',
field: 'people',
cellRenderer: (params: any) => {
if (!params || !params.value || params.value.length <= 0)
return '';
let titles = '';
params.value.forEach(element => {
if (element.name) {
titles += element.name + ',';
}
});
return titles.substring(0, titles.length - 1);
}
}
);
}
Above there's example of two columns: one with timestamp, one with object.
My export() method which I use to export as csv:
export() {
let header = this.columnDefs.map(columnDef => {
let id = columnDef.field || columnDef.colId || columnDef.value;
let headerName = columnDef.headerName;
return headerName;
});
let a: any;
let params: any = {
fileName: 'export.csv',
columnSeparator: ';',
skipHeader: true,
columnKeys: this.columnDefs.map(c => c.field || c.colId).filter(c => !!c)
};
params.customHeader = header.join(params.columnSeparator) + '\n';
this.grid.api.exportDataAsCsv(params);
}
However, I have trouble finding how format values before exporting, because here I only get header and field and no value?
And when I export my grid to csv instead of datetime I get e.g.
which is timestamp and for my object I get
Instead of having Tom, Bob, Ben
Does anyone know how to format these values before exporting?
In your export() function, you will have to add a parameter processCellCallback.
Something like this:
export() {
let header = this.columnDefs.map(columnDef => {
let id = columnDef.field || columnDef.colId || columnDef.value;
let headerName = columnDef.headerName;
return headerName;
});
let a: any;
let params: any = {
fileName: 'export.csv',
columnSeparator: ';',
skipHeader: true,
columnKeys: this.columnDefs.map(c => c.field || c.colId).filter(c => !!c)
};
params.customHeader = header.join(params.columnSeparator) + '\n';
params.processCellCallback = function(cellParams) {
if(cellParams && cellParams.column.colId === 'yourTimestampfield') {
return this.formatter; //apply your timestamp formatter
} else if(cellParams && cellParams.column.colId === 'yourObjectfield') {
return this.formatter; //apply your object formatter
} else
return cellParams.value // no formatting
}
this.grid.api.exportDataAsCsv(params);
}
Read more in the example and docs here.
I am running a loop through my array to check if calendar and tpoint have values. In my else statement of my if-statement I am attempting to get the key's name with var notSelected = (obj.prop.subProp).val() !== '';.
I know I am off with my method.. I am just unsure how to get the key name.
So, with my example, since the values in tpoint are empty, I am wanting the var notSelected to equal tpoint.
Anyone know how I can do this?
var packageContents = {
'packages': [
{
'price': '23',
'name': 'Bronze Bundle Package',
'calendar': {
'type': '2year',
'color': 'Brushed Nickel',
},
'tpoint': {
'type': '',
'touches': '',
'years': '',
}
}
]
};
var bundleSet = null;
var bundleSet = null;
packageContents.packages.forEach(function (obj) {
for (var prop in obj) {
if (prop === 'calendar' || prop === 'tpoint') {
for (var subProp in obj[prop]) {
if (obj[prop][subProp] !== '') {
bundleSet = true;
} else {
bundleSet = false;
var notSelected = (obj.prop.subProp).val() !== '';
console.log(notSelected);
}
}
}
}
console.log(bundleSet);
});
What about something like this:
function hasEmptyProps(prop) {
return Object.values(prop).some(x => x === '');
}
const result = packageContents.packages.map(x => {
if (hasEmptyProps(x.calendar)) {
return 'calendar';
} else if (hasEmptyProps(x.tpoint)) {
return 'tpoint'
} else {
return '';
}
})
console.log(result)
Would return ["tpoint"] (or an array of "calendar", "", or "tpoint")