Guy Messika Guy Messika - 4 months ago 15
Javascript Question

How to iterate over an object from an SNMP device and create a readable output using predefined rules

I have the following JSON out of an SNMP device:

mib = [
"1.3.6.1.2.1.43.11.1": {
"1.1": {
"3": "1",
"5": "3",
"6": "Cyan Toner Cartridge, WorkCentre 6505N",
"8": "2000",
"9": "800"
},
"1.2": {
"3": "2",
"5": "3",
"6": "Magenta Toner Cartridge, WorkCentre 6505N",
"8": "1000",
"9": "400"
},
"1.5": {
"3": "0",
"5": "9",
"6": "Imaging Unit, WorkCentre 6505N",
"8": "24000",
"9": "24000"
}
},
"1.3.6.1.2.1.43.12.1": {
"1.1": {
"4": "cyan"
},
"1.2": {
"4": "magenta"
}
}
]


the result I want out of it is this:

device["markerSupplies"]: [
0: {
color: "cyan",
type: "toner",
description: "Cyan Toner Cartridge, WorkCentre 6505N",
capacity: "2000",
value: "800"
},
1: {
color: "magenta",
type: "toner",
description: "Magenta Toner Cartridge, WorkCentre 6505N",
capacity: "1000",
value: "400"
},
2: {
color: "",
type: "opc",
description: "Imaging Unit, WorkCentre 6505N",
capacity: "24000",
value: "24000"
},
]


"1.1", "1.2"... are just indexes I have information about what's going inside of them.
every property inside of them called a column and is corresponding to its index.

I know the following about the columns of each table:

1.3.6.1.2.1.43.11.1
3 the color index inside 1.3.6.1.2.1.43.12.1
5
3 "toner"
9 "opc"
6 description
8 capacity
9 level

1.3.6.1.2.1.43.12.1
4 color name


how can I create a JSON information object that using a javascript code I can iterate over the JSON from the device
and create the output result I showed above?

Answer

You could use some helper variables for color and type and iterate over the keys to build a new array.

var mib = { "1.3.6.1.2.1.43.11.1": { "1.1": { 3: "1", 5: "3", 6: "Cyan Toner Cartridge, WorkCentre 6505N", 8: "2000", 9: "800" }, "1.2": { 3: "2", 5: "3", 6: "Magenta Toner Cartridge, WorkCentre 6505N", 8: "1000", 9: "400" }, "1.5": { 3: "0", 5: "9", 6: "Imaging Unit, WorkCentre 6505N", 8: "24000", 9: "24000" } }, "1.3.6.1.2.1.43.12.1": { "1.1": { 4: "cyan" }, "1.2": { 4: "magenta" } } },
    cols = { 3: 'color', 5: 'type', 6: 'description', 8: 'capacity', 9: 'level' },
    types = { 3: 'toner', 9: 'opc' },
    markerSupplies = mib['1.3.6.1.2.1.43.11.1'],
    colors = mib['1.3.6.1.2.1.43.12.1'],
    result = Object.keys(markerSupplies).map(function (k) {
        var o = {};
        Object.keys(cols).forEach(function (c) {
            if (c === '3') {
                o[cols[c]] = (colors[k] || {})['4'] || '';
                return;
            }
            if (c === '5') {
                o[cols[c]] = types[markerSupplies[k][c]] || '';
                return;
            }
            o[cols[c]] = markerSupplies[k][c] || '';

        });
        return o;
    });

console.log(result);