Create Objects from variable name

45 Views Asked by At

I am using the S7-node to get data from SIEMENS PLC I have a huge list of data to take out and I would to recreate an object I tried to name the variable as :

line1.color.value
line1.speed.value
line2.color.value
line2.speed.value

if i try to get the values with msg.payload.line1.color.value is it not working, there is no object corresponding.

I would like to automatically create the objects line1,line2... following the name of the variable. Is there a way to do it ?

1

There are 1 best solutions below

0
Nicky On

1. set function

To implement a 'set' function similar to the one in Lodash, you can use recursion to handle nested properties. Here's a simple JavaScript implementation:

function set(obj, path, value) {
  if (typeof path === 'string') {
    path = path.split('.');
  }

  if (path.length === 1) {
    obj[path[0]] = value;
    return obj;
  }

  const currentKey = path.shift();
  obj[currentKey] = obj[currentKey] || {};

  return set(obj[currentKey], path, value);
}

// eg:
const obj = {};
set(obj, 'a.b.c', 42);
console.log(obj); // output: { a: { b: { c: 42 } } }

This 'set' function takes the object, the path, and the value to be set as parameters. If the path is a string, it is split into an array of paths. Recursively create nested properties and set the given value at the end of the path.

2. use set function

set(msg.payload,'line1.color.value',1);
set(msg.payload,'line2.color.value',2);
set(msg.payload,'line3.color.value',3);