【问题标题】:Create a collection of js objects by deserialising a collection of json objects in node.js通过反序列化 node.js 中的 json 对象集合来创建 js 对象集合
【发布时间】:2018-01-31 07:50:35
【问题描述】:

我有一个原型类:

function temp(){
    this.a=77;
}

temp.prototype.getValue = function(){
    console.log(this.a);
}

还有一个 json 对象数组:

var x=[{a:21},{a:22},{a:23}];

有没有什么方法可以直接使用 json 对象数组来实例化类temp 的数组,类似于泛型帮助我们在 Java 中使用 Jackson TypeReference 实现的方式。

var y= new Array(new temp());
//something similar to what Object.assign achieves for a single object 

因此它可以扩展到其他对象集合,例如Map<obj1,obj2>等。

【问题讨论】:

    标签: javascript java json node.js jackson


    【解决方案1】:

    在 Javascript 中没有内置的方法可以做到这一点。对您的数据或构造函数进行一些假设,您可以相当简单地创建自己的函数来创建这样的数组:

    // pass the constructor for the object you want to create
    // pass an array of data objects where each property/value will be copied
    // to the newly constructed object
    // returns an array of constructed objects with properties initialized
    function createArrayOfObjects(constructorFn, arrayOfData) {
        return arrayOfData.map(function(data) {
            let obj = new constructorFn();
            Object.keys(data).forEach(function(prop) {
               obj[prop] = data[prop];
            });
            return obj;
        });
    }
    

    或者,您可以创建一个构造函数,该构造函数接受一个数据对象,然后从该对象初始化自身:

    // pass the constructor for the object you want to create
    // pass an array of data objects that will each be passed to the constructor
    // returns an array of constructed objects 
    function createArrayOfObjects(constructorFn, arrayOfData) {
        return arrayOfData.map(function(data) {
            return new constructorFn(data);
        });
    }
    
    // constructor that initializes itself from an object of data passed in
    function Temp(data) {
        if (data && data.a) {
            this.a = data.a;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用Array.from 直接用Temp 的实例填充数组。

      function Temp(){
          this.a=77;
      }
      
      Temp.prototype.getValue = function(){
          console.log(this.a);
      }
      
      var array = Array.from({ length: 5 }, _ => new Temp);
      
      array[0].a = 42;
      console.log(array);

      【讨论】:

        【解决方案3】:

        如果你正在使用 NPM,我强烈推荐 linq-collections 包来处理这类事情。

        https://www.npmjs.com/package/linq-collections

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多