This code works for converting the JSON to an object where each name object turns into the key for either its value, or if it instead has its own element object breaks that out and does the same to its contents.
Is there a better way to do this that would also allow for more extensiblity of the JSON schema?
Is there a way I can get it all down to a simpler function that I can pass the first element and have it convert it down to whatever depth the schema goes?
const fs = require('fs');
{
let scheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version='1.0'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root;
let depth = 0;
var compiled = {
[scheme.ele.name]: scheme.ele.ele.map(function(i) {
if (typeof i.ele != 'undefined') {
return {
[i.name]: i.ele.map(function(k) {
if (typeof k.ele != 'undefined') {
return {
[k.name]: k.ele.map(function(p) {
if (typeof p.ele != 'undefined') {
return {
[p.name]: p.ele
};
} else {
return {
[p.name]: p.value
};
}
})
};
} else {
return {
[k.name]: k.value
};
}
})
};
} else {
return {
[i.name]: i.value
};
}
})
};
}
console.log(JSON.stringify(compiled, 0, 2));
I should add, this is intended to eventually also apply validation and grab real data when it gets to the string objects.
The output looks like this:
{
"REPORT": [
{
"SEGMENT0": [
{
"NUMBER1": ""
},
{
"NUMBER2": ""
}
]
},
{
"SEGMENT1": [
{
"RECORD1": [
{
"NUMBER1": ""
},
{
"NUMBER2": ""
}
]
}
]
},
{
"SEGMENT2": []
},
{
"SEGMENT3": []
},
{
"SEGMENT4": []
},
{
"SEGMENT5": []
}
]
}
You could destructure the object, get name, ele and value and return a new object with name as key and either an array by mapping the objects of ele or the value.
const
getData = ({ name, ele, value }) => ({
[name]: Array.isArray(ele)
? ele.map(getData)
: value
});
var scheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version=\'1.0\'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root,
result = getData(scheme.ele);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina's answer is cleaner but this looks a bit more like your code so I figured I'd post it anyway.
let scheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version=\'1.0 \'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":"1"}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":"2"},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root;
let newScheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version=\'1.0 \'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":"1"},{"name":"NUMBER2","value":"3"}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":"4"},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root;
//Yay, recursion!
function mapObj(a, o = {}) {
let array = o[a.name] || [];
for (let i = 0; i < a.ele.length; i++) {
let b = a.ele[i];
array[i] = b.ele ?
mapObj(b, array[i]) : {
[b.name]: b.value
};
}
o[a.name] = array;
return o;
}
let obj = mapObj(scheme.ele);
console.log(obj);
console.log(mapObj(newScheme.ele, obj));
JSFiddle version with spacing: http://jsfiddle.net/eopth925/1/
var obj = {
test: {
test2: "test",
test3: {
base: {
base: {
check: function() {
return this;
},
va: function() {
return "value";
},
do: "this is dummy"
}
}
},
test4: {
test5: function() {
var k = 2;
k++;
return k;
},
test6: {
test7: {
test8: "test8",
test9: {
test10: "test10",
test11: function() {
return window.jQuery;
},
test12: "test12",
test13: function() {
return window.ga;
}
}
}
}
}
},
};
var output = "";
var addbreak = "\n";
var RunFunc = {
propertypri: function(a) {
Object.keys(a).forEach(function(e) {
if (typeof a[e] === 'object') {
output += `Main Key=${e}`;
RunFunc.propertyobj(e, a[e]);
}
else {
output += `Main Key=${e} value=${a[e]}` + addbreak;
}
});
console.log(output);
},
propertyobj: function(key, keyObj) {
Object.keys(keyObj).forEach(function(e) {
if (typeof keyObj[e] === 'object') {
output += ` Subkey=${e}`;
RunFunc.propertyobj(e, keyObj[e]);
}
else {
output += ` Subkey=${e} value=${keyObj[e]}` + addbreak;
}
});
}
};
RunFunc.propertypri(obj);
The way it's outputting is not view friendly. I would like to add proper indentation in the output. I am sure there is a more efficient way of doing what I am trying to accomplish.
How can I update my script so it displays like this:
Main Key=test
Subkey=test2 value=test
Subkey=test3
Subkey=base
Subkey=base
Subkey=check value=function() {
return this;
}
Subkey=va value=function() {
return "value";
}
Subkey=do value=this is dummy
Subkey=test4
Subkey=test5 value=function() {
var k = 2;
k++;
return k;
}
Subkey=test6
Subkey=test7
Subkey=test8 value=test8
Subkey=test9
Subkey=test10 value=test10
Subkey=test11 value=function() {
return window.jQuery;
}
...
Why not just use JSON.stringify?
console.log(JSON.stringify(foo, (key, val) => (typeof val === 'function' ? '' + val : val), 2))
const yourObject = { /* object properties here */ }
function printKeys(obj) {
if (typeof obj === 'object') {
const keys = Object.keys(obj)
for (const key of keys) {
printKeys(key)
}
} else {
console.log(obj)
}
}
var options = {
url: function (phrase) {
return "location/autoComplete?key=" + phrase;
},
getValue: "cityName",
template: {
type: "custom",
method: function (value, item) {
return value + ", " + item.stateName;
}
},
list: {
onClickEvent: function () {
var selectedLongitude = $("#autoCompleteSearch").getSelectedItemData().longitude;
var selectedLatitude = $("#autoCompleteSearch").getSelectedItemData().latitude;
userPos = {
lat: Number(selectedLatitude),
lng: Number(selectedLongitude)
};
map.setCenter(userPos);
map.setZoom(17)
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 400,
callback: function () {
}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 400,
callback: function () {
}
}
}
};
This is the code I am using right now to fetch a remote webservice data. Now I need to get the data and remove the duplicate "city names". Also I need to show "Data not available" or some custom method when there is no data from the webservice. I am kind of stuck. Would be great if someone could point me on how to achieve this.
You can get rid of duplicates using a helper function:
function removeDuplicates(input) {
if (!input) { //Falsy input
return input;
}
var isArray = Array.isArray(input) ? [] : {};
var items = [];
var output = {};
for (var key in input) {
if (items.indexOf(input[key]) < 0) {
items.push(input[key]);
if (!isArray) {
output[key] = input[key];
}
}
}
return isArray ? items : output;
}
You can show your custom text if Array.isArray(input) ? (input.length === 0) : (Object.keys(input).length === 0 && input.constructor === Object).
From the link qr-code.js I have the code below.
Then I don't understand, on the highlighted line (60), what means the suffix: "Changed"?
attributeChangedCallback: {
value: function (attrName, oldVal, newVal) {
var fn = this[attrName+'Changed'];
if (fn && typeof fn === 'function') {
fn.call(this, oldVal, newVal);
}
this.generate();
}
Also I don't understand the usage of:
this[attrName+'Changed']
Could you explain me this?, I don't find any clear explanation about this on Google. Thanks.
Below is the full code:
'use strict';
(function(definition) {
if (typeof define === 'function' && define.amd) {
define(['QRCode'], definition);
} else if (typeof module === 'object' && module.exports) {
var QRCode = require('qrjs');
module.exports = definition(QRCode);
} else {
definition(window.QRCode);
}
})(function(QRCode) {
//
// Prototype
//
var proto = Object.create(HTMLElement.prototype, {
//
// Attributes
//
attrs: {
value: {
data: null,
format: 'png',
modulesize: 5,
margin: 4
}
},
defineAttributes: {
value: function () {
var attrs = Object.keys(this.attrs),
attr;
for (var i=0; i<attrs.length; i++) {
attr = attrs[i];
(function (attr) {
Object.defineProperty(this, attr, {
get: function () {
var value = this.getAttribute(attr);
return value === null ? this.attrs[attr] : value;
},
set: function (value) {
this.setAttribute(attr, value);
}
});
}.bind(this))(attr);
}
}
},
//
// LifeCycle Callbacks
//
createdCallback: {
value: function () {
this.createShadowRoot();
this.defineAttributes();
this.generate();
}
},
attributeChangedCallback: {
value: function (attrName, oldVal, newVal) {
var fn = this[attrName+'Changed'];
if (fn && typeof fn === 'function') {
fn.call(this, oldVal, newVal);
}
this.generate();
}
},
//
// Methods
//
getOptions: {
value: function () {
var modulesize = this.modulesize,
margin = this.margin;
return {
modulesize: modulesize !== null ? parseInt(modulesize) : modulesize,
margin: margin !== null ? parseInt(margin) : margin
};
}
},
generate: {
value: function () {
if (this.data !== null) {
if (this.format === 'png') {
this.generatePNG();
}
else if (this.format === 'html') {
this.generateHTML();
}
else if (this.format === 'svg') {
this.generateSVG();
}
else {
this.shadowRoot.innerHTML = '<div>qr-code: '+ this.format +' not supported!</div>'
}
}
else {
this.shadowRoot.innerHTML = '<div>qr-code: no data!</div>'
}
}
},
generatePNG: {
value: function () {
try {
var img = document.createElement('img');
img.src = QRCode.generatePNG(this.data, this.getOptions());
this.clear();
this.shadowRoot.appendChild(img);
}
catch (e) {
this.shadowRoot.innerHTML = '<div>qr-code: no canvas support!</div>'
}
}
},
generateHTML: {
value: function () {
var div = QRCode.generateHTML(this.data, this.getOptions());
this.clear();
this.shadowRoot.appendChild(div);
}
},
generateSVG: {
value: function () {
var div = QRCode.generateSVG(this.data, this.getOptions());
this.clear();
this.shadowRoot.appendChild(div);
}
},
clear: {
value: function () {
while (this.shadowRoot.lastChild) {
this.shadowRoot.removeChild(this.shadowRoot.lastChild);
}
}
}
});
//
// Register
//
document.registerElement('qr-code', {
prototype: proto
});
});
As #Jhecht suggested, it's a combination of the name of a attribute and the suffix "Changed" in order to create generic method names.
For example if the <qr-code> element has an attribute "foo" that is added, updated or removed, then the callback will define the fn variable to this["fooChanged"], which is equivalent to this.fooChanged.
If this method exists, it will be invoked by fn.call().
However I see nowhere in the code you posted such method signature attached to the custom element prototype, so it's useless code until further notice.
I have a straightforward "extend" method set up like this:
extend: function(source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
myThing[k] = source[k];
}
}
return myThing;
}
You use it like
myThing.extend({
newObj: {
myFunc: function () { console.log('things'); }
}
});
and it works great.
However, I would love to add the ability to have some other piece of code call this LATER:
myThing.extend({
newObj: {
mySecondFunc: function () { console.log('things'); }
}
});
and I should be able to call both myThing.newObj.myFunc() AND myThing.newObj.mySecondFunc().
I tried changing it to this:
for (var k in source) {
if (source.hasOwnProperty(k)) {
if (mtUtils.hasOwnProperty(k)) {
for (var t in k) {
mtUtils[k][t] = source[k][t];
}
} else {
mtUtils[k] = source[k];
}
}
}
but that doesn't seem to work.
function extend(dest, source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
var value = source[k];
if (dest.hasOwnProperty(k) && typeof dest[k] === "object" && typeof value === "object") {
extend(dest[k], value);
} else {
dest[k] = value;
}
}
}
return dest;
}
var myThing = {};
extend(myThing, {
newObj: {
myFunc: function() {
console.log('things');
}
}
});
extend(myThing, {
newObj: {
mySecondFunc: function() {
console.log('things');
}
}
});
myThing;
/*
Object
newObj: Object
myFunc: function () { console.log('things'); }
mySecondFunc: function () { console.log('things'); }
__proto__: Object
__proto__: Object
*/
This should fix your problem, but why not implement a recursive version of extend?
for (var k in source) {
if (source.hasOwnProperty(k)) {
if (mtUtils.hasOwnProperty(k)) {
for (var t in source[k]) {
mtUtils[k][t] = source[k][t];
}
} else {
mtUtils[k] = source[k];
}
}
}