gpt4 book ai didi

javascript - 将 JSON 映射到 ES6 类

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:31:54 25 4
gpt4 key购买 nike

我将我们的工作人员保存在一个 json 文件中,并想到将这些数据用于 ES6 类。我处理得越多,我就越觉得自己可能遗漏了什么。我在 coffeescript 中这样工作:

fetch  = require('node-fetch')
domain = 'domain.com'
apiSrc = 'api.domain.com'
slug = 'people'

class Person
constructor: (json) -> {name: @name, title: @title, school: @school, bio: @bio} = json
email: (username) ->
username.replace(/\s/, '.').toLowerCase() + '@' + domain
profile: ->
content = []
if this.name then content.push("#{@name}")
if this.title then content.push("#{@title}")
if this.school then content.push(school) for school in "#{@school}"
if this.bio then content.push("#{@bio}")
if this.name then content.push(this.email("#{@name}"))
content.join('')

fetch('http://' + apiSrc + '/' + slug + '.json')
.then((response) -> response.json())
.then((api) ->
content = []
group = []
group.push(new Person(them)) for them in api[slug]
for them, index in group
content.push(them.profile())
console.log(content.join(''))
)

但后来我想如果我能把它转换成 ES6 会更好。我知道用例很简单,类当然不是必需的,因为我只是将数据用于模板,但是,为了学习,我尝试这样做。我会以错误的方式解决这个问题吗?现在,我觉得应该有一种方法可以返回我放入 Person 类中的所有“人”。但是,我唯一能弄清楚如何做到这一点的方法是运行一个 for 循环,然后将其写入文档。

class Person {
constructor(data) { ({name: this.name, title: this.title, school: this.school, bio: this.bio, email: email(this.name)} = data); }
email(username) {
return username.replace(/\s/, '.').toLowerCase() + '@' + location.hostname.replace(/[^\.\/\@]+\.[^\.\/]+$/, '');
}
profile() {
return `${this.name} ${this.title}`;
}
}

var apiSrc = 'api.domain.com';
var slug = 'people';
fetch(`http://${apiSrc}/${slug}.json`)
.then(function(response) { return response.json() }) // .then(response => response.json())
.then(function(api) {
var content = [];
var group = [];
for (var i = 0; i < api[slug].length; i++) { var them = api[slug][i]; new Person(them); }
for (var i = 0; index < group.length; i++) {
var them = group[i];
content.push(them.profile());
console.log(content.join(''));
}
});

我的 ES6 转换实际上现在甚至无法正常工作。 API 返回 JSON 但之后它变得困惑。任何建议都会非常有帮助,因为我正在努力提高自己作为编码员的水平,并希望这种示例可以帮助其他人在实际用例中学习类。

最佳答案

您可以尝试使用 reviver JSON.parse 的参数。这是一个简化的示例:

class Person {
// Destructure the JSON object into the parameters with defaults
constructor ({name, title, school=[]}) {
this.name = name
this.title = title
this.school = school
}
}

var api = JSON.parse(a, function (k,v) {
// Is this a new object being pushed into the top-level array?
if (Array.isArray(this) && v.name) {
return new Person(v)
}
return v
})

var group = api["people/administration"]

关于javascript - 将 JSON 映射到 ES6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37928113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com