Skip to content

Instantly share code, notes, and snippets.

@fuglu
Last active May 22, 2020 15:22
Show Gist options
  • Save fuglu/5df0b0d51c5640220c945aff26390e7b to your computer and use it in GitHub Desktop.
Save fuglu/5df0b0d51c5640220c945aff26390e7b to your computer and use it in GitHub Desktop.
var msg = {};
msg.payload = {
value_id: "2-37-1-0",
node_id: 2,
class_id: 37,
type: "bool",
genre: "user",
instance: 1,
index: 0,
label: "Switch",
units: "",
help: "Turn On/Off Device",
read_only: false,
write_only: false,
min: 0,
max: 0,
is_polled: false,
value: true,
lastUpdate: 1589486874669,
};
var newMsg = {};
var tags = {};
// Ist es richtig, dass payload ein array werden soll?
newMsg.payload = [
{
// geht
value: msg.payload.value,
// geht nicht, soll aber gehen!!
//msg.payload.label: msg.payload.value
// So?
label: msg.payload.value,
// Use msg.payload.value as key
[msg.payload.label]: msg.payload.value
},
{
node_id: msg.payload.node_id,
class_id: msg.payload.class_id,
},
];
// Alternative:
// Copy old msg object
var msgCopy = Object.assign({}, msg);
// Delete old (unused) key
delete msgCopy.payload.value;
// Create new key from old msg object
msgCopy.payload.label = msg.payload.value;
// Das delete kannst du natürlich auch direkt auf dem alten msg object machen und es einfach wiederverwenden:
// msg.payload.label = msg.payload.value;
// delete msg.payload.value;
console.log(newMsg);
console.log(msgCopy);
return newMsg;
@boettner
Copy link

boettner commented May 22, 2020

Ich hab mir schon sowas ergooglet:

msg.payload = {"value_id":"2-37-1-0","node_id":2,"class_id":37,"type":"bool","genre":"user","instance":1,"index":0,"label":"Switch","units":"","help":"Turn On/Off Device","read_only":false,"write_only":false,"min":0,"max":0,"is_polled":false,"value":true,"lastUpdate":1589486874669}

var newMsg = {};
var tags = {};

tags['payload'] = [
    {
        value: msg.payload.value
    }
];

newMsg.payload = [
    {
        node_id: msg.payload.node_id,
        class_id: msg.payload.class_id
    }
];

function renameKey(obj, old_key, new_key) {
    if (old_key !== new_key) {
        Object.defineProperty(obj, new_key, Object.getOwnPropertyDescriptor(obj, old_key));
        delete obj[old_key];
        return obj;
    }
}

tags.payload.forEach(obj => renameKey(obj, 'value', msg.payload.label));

console.log(tags);
console.log(newMsg);

var newObj = {...newMsg, ...tags}

console.log(newObj);

return newObj;

Output

{ payload: [ { Switch: true } ] }
{ payload: [ { node_id: 2, class_id: 37 } ] }
{ payload: [ { Switch: true } ] }

aber da wird beim Anlegen von newObj der payload von newMsg mit dem payload von tags überschrieben, sodass ich nur key-values aus dem einen oder dem anderen Objekt haben kann...

@boettner
Copy link

Junge! Wenn du die Tränen in meinen Augen sehen könntest... ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment