简体   繁体   English

Node.js从JSON创建模型对象

[英]Node.js creating model objects from json

I know that any json can be easily parsed into a javascript object, but let's say, I am using github API to get the profile of a couple developers, but I want to add to this objects some methods to process some data of those developers and keep the info within the object. 我知道任何json都可以轻松地解析为javascript对象,但可以说,我正在使用github API获取几个开发人员的资料,但是我想向该对象添加一些方法来处理这些开发人员的一些数据,将信息保留在对象内。

I know mongoose is a good extension that implements the concept of models that can do something similar to what I desire, but on a different approach, using as it uses a database to retrieve the models data. 我知道猫鼬是一个很好的扩展,它实现了模型的概念,可以执行与我期望的操作类似的操作,但是使用不同的方法,因为它使用数据库来检索模型数据。 Is there a way to populate an array of models using a json returned from an API? 有没有一种方法可以使用从API返回的json填充模型数组?

Maybe my way of approaching this matter is not correct, but I fail to see another way out of this issue. 也许我处理此问题的方法不正确,但是我看不到解决该问题的另一种方法。

Thank you for your help 谢谢您的帮助

I don't know if this is what you are asking but you can parse JSON: 我不知道这是您要的内容,但是您可以解析JSON:

getSomethingFromAPI().then(function(dataResponse){
   var objectArray = JSON.parse(dataResponse)
})

If it isn't please post some code snippets and clarify your questions. 如果不是,请发布一些代码段并阐明您的问题。

Per comment: I don't think you can freely add an instance method without writing some code. 每条评论:我认为您可以在不编写一些代码的情况下自由添加实例方法。 It could be as simple as taking the parse, and mapping that into instances (using underscore): 它可能像解析一样简单,然后将其映射到实例中(使用下划线):

var someMethod = function(){
    return this.x
}

getSomethingFromAPI().then(function(dataResponse){
   var objectArray = _.map(JSON.parse(dataResponse), function(anObject){
      anObject.someMethod = someMethod.bind(anObject)
      return anObject
   })
})

There you could also instantiate object via constructors in the map, 在那里,您还可以通过地图中的构造函数实例化对象,

getSomethingFromAPI().then(function(dataResponse){
   var objectArray = _.map(JSON.parse(dataResponse), function(anObject){
      return new SomeObjectConstructor(anObject.x, anObject.y)
   })
})

or perhaps there are more advanced techniques. 也许还有更先进的技术。 A functional approach would keep the data and the methods separated... 一种实用的方法可以将数据和方法分开...

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

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