简体   繁体   English

将 K、V 对分配给 NodeJS 中的 JSON 对象

[英]Assigning K,V pairs to a JSON object in NodeJS

I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.我有一个 NodeJS 脚本,它以“键、值”对的形式从源中获取数据,我想将该数据放入 JSON 对象中。

I am using SNMP to get the k, v pairs, where the key is the OID.我正在使用 SNMP 来获取 k、v 对,其中密钥是 OID。 I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.我想然后将这些值映射到 JSON 对象上,而不必针对已知值迭代检查每个 OID。

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data. k,v 对就这样存储在对象中,我对这些传入数据没有灵活性。

let pair = {
    key: "abc...",
    value: "xyz..."
}

I have defined the JSON object as an empty structure.我已将 JSON 对象定义为空结构。

let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}

And I iterate through my keys ( pairs is the name of an array containing the k,v objects)我遍历我的键( pairs是包含 k,v 对象的数组的名称)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}

I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.我想知道是否有任何方法可以简化这一点,因为我有大约 200 个要处理的键(上面的代码只是一个示例),并且对我来说迭代每个可能的键似乎并不是特别优化。

EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.编辑:jsonObject 比此处显示的复杂得多,有很多层,并且键的名称与 json 对象属性名称不匹配 1:1,如图所示。

EDIT 2: This seems like an odd situation, I know.编辑 2:我知道,这似乎是一种奇怪的情况。 For example, I want to take the K,V input:例如,我想取 K,V 输入:

Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"

And convert it to a dissimilarly named JSON object并将其转换为名称不同的 JSON 对象

{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}

Potentially using some form of mapping, instead of using ~200 if statements可能使用某种形式的映射,而不是使用 ~200 个 if 语句

Use the Array.prototype.reduce function.使用Array.prototype.reduce函数。

const { name, ...properties } = pairs.reduce(
  (obj, { key, value }) => Object.assign(obj, { [key]: value }),
  {}
)

const obj = { name, properties }

Reduce will reduce an array into a scalar, in this case an object with all k,v pairs as fields with values on an object, starting with {} as a default value the merging each k,v pair 1 at a time. Reduce 会将数组缩减为标量,在这种情况下,一个对象将所有 k,v 对作为具有对象上的值的字段,以{}作为默认值开始,一次合并每个 k,v 对 1。

Object.assign will merge objects, overwriting objects on the left with the fields of keys of objects on the right. Object.assign将合并对象,用右侧对象的键字段覆盖左侧的对象。

And finally the syntax to dynamically add a key on an object literal is { [k]: v }最后,在对象文字上动态添加键的语法是{ [k]: v }

By the way this is a useful trick for reducing the complexity of algorithms where you need to look up values in an array in a loop.顺便说一句,这是降低算法复杂性的有用技巧,您需要在循环中查找数组中的值。 Simply create an index of one array then in the loop, lookup in the index instead.只需创建一个数组的索引,然后在循环中,改为在索引中查找。

You can use Array.prototype.forEach for iterating and assigning the object.您可以使用Array.prototype.forEach来迭代和分配对象。

 const jsonObject = { name: '', properties: { email: '', address: '', town: '' } }; const pairs = [{key: 'name', value: 'thatsimplekid'}, {key: 'email', value: 'aaa@domain.com'}, {key: 'town', value: 'myTown'}, {key: 'address', value:'123 main st' }]; pairs.forEach( ({key, value}) => jsonObject.hasOwnProperty(key) ? jsonObject[key] = value : jsonObject.properties[key] = value); console.log(jsonObject);

   for (let i = 0; i < pairs.length; i++) {
      const key = pairs[i].key;
      const value = pairs[i].value;

      if (pairs[i].key == "name") {
        jsonObject[key] = value;
      } else {
        jsonObject.properties[key] = value;
      }
    }

After the 'name' all values goes to the properties object, so a simple if would do it在“名称”之后,所有值都转到属性对象,所以一个简单的 if 就可以了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM