-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a labels array "serializer/deserializer" #483
Labels
Comments
Improved version: const util = require("util");
function arrayToObject(labels) {
let result = {};
labels.forEach((label, i) => {
let [path, value] = label.split("=");
let parts = path.split('.');
let current = result;
for (let i = 0; i < parts.length; i++) {
let key = parts[i];
let isLast = (i === parts.length - 1);
let isArray = key.endsWith('[]');
if (isArray) {
key = key.slice(0, -2);
}
if (isLast) {
//value = (value === "true") ? true : (value === "false") ? false : value;
if (isArray) {
if (!current[key]) {
current[key] = [];
}
current[key].push(value);
} else {
current[key] = value;
}
} else {
if (!current[key]) {
current[key] = {};
}
current = current[key];
}
}
});
return result;
}
function objectToArray(obj, prefix = "") {
let result = [];
for (let key in obj) {
let value = obj[key];
let newKey = prefix ? `${prefix}.${key}` : key;
if (typeof value === 'object' && !Array.isArray(value)) {
result = result.concat(objectToArray(value, newKey));
} else if (Array.isArray(value)) {
value.forEach(val => {
result.push(`${newKey}[]=${val}`);
});
} else {
result.push(`${newKey}=${value}`);
}
}
return result;
}
const json = {
timemstamp: Date.now(),
bool: true,
zero: null,
obj: {
str: "Hello from json"
}
}
// Beispielaufruf
let labels = [
"oh.notifications.smtp.enabled=true",
"oh.notifications.smtp.topic=Hello World",
"[email protected]", // wrong - gerts converted to object instead of string
"oh.notifications.enabled=true",
"oh.notifications.states[]=foo",
"oh.notifications.states[]=bar",
"oh.history.states[]=*",
"oh.history.duration=3600",
"private=true",
"my-super-label=value",
`oh.json=${JSON.stringify(json)}`
];
console.log("labels", labels)
/*
const ohLabels = labels.filter((label) => {
return !label.startsWith("oh.");
});
*/
const parsedObj = arrayToObject(labels);
const arrayFromObj = objectToArray(parsedObj);
console.log("parsedObj", util.inspect(parsedObj, false, 100, true));
console.log("arrayFromObj", arrayFromObj);
const same = (() => {
let valid = labels.every((label) => {
return arrayFromObj.includes(label);
});
valid &= arrayFromObj.length === labels.length;
return Boolean(valid);
})();
console.log("Array same", same); Result:
|
For what purpose? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Convert label(s) dot notoation to a object.
e.g.
will be:
Could be added as static methods to the
Labels
class (class.labels.js)The text was updated successfully, but these errors were encountered: