Javascript 获取数据并向Json对象添加标题
我想为我的JSON对象添加标题,我希望实现的结构是:Javascript 获取数据并向Json对象添加标题,javascript,arrays,json,object,Javascript,Arrays,Json,Object,我想为我的JSON对象添加标题,我希望实现的结构是: { "posts": [ { "title": "put title here", "upvotes": 1234, "score": 1000, "num_comments": 100, "created": "16.05.2019 12:12", }, ] } 我能够获取数据并将其放入26个元素的数组中,一切都很好,但我希望以某种方式添加“p
{
"posts": [
{
"title": "put title here",
"upvotes": 1234,
"score": 1000,
"num_comments": 100,
"created": "16.05.2019 12:12",
},
]
}
我能够获取数据并将其放入26个元素的数组中,一切都很好,但我希望以某种方式添加“posts:”以超越整个rest,以下是我的代码:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = {title, upvote, score, comments, created}
postList.push(allPosts)
return postList
})
console.log(posts);
return posts
})
您可能需要创建如下所示的对象 {propertyName:value}
您可能需要创建如下所示的对象 {propertyName:value}
您可以尝试以下代码
fetch(“https://www.reddit.com/r/funny.json")
.then(resp=>resp.json())
。然后(res=>({
posts:res.data.children.map(el=>({
标题:el.data.title,
upvote:el.data.upvote,
分数:el.data.score,
注释:el.data.num_注释,
创建:el.data.created
}))
}))
。然后(posts=>{
控制台日志(posts);
});代码>您可以尝试以下代码
fetch(“https://www.reddit.com/r/funny.json")
.then(resp=>resp.json())
。然后(res=>({
posts:res.data.children.map(el=>({
标题:el.data.title,
upvote:el.data.upvote,
分数:el.data.score,
注释:el.data.num_注释,
创建:el.data.created
}))
}))
。然后(posts=>{
控制台日志(posts);
});代码>您可以这样做:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
return {
title: el.data.title,
upvote: el.data.ups,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}
})
const postObject = { posts }
console.log(postObject);
return postObject
})
映射函数返回值,通过这种方式可以得到一个带有键(posts)和值(带有细节的对象)的对象。您可以这样做:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
return {
title: el.data.title,
upvote: el.data.ups,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}
})
const postObject = { posts }
console.log(postObject);
return postObject
})
Map函数返回值,通过这种方式可以得到一个包含键(posts)和值(包含细节的对象)的对象
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(async res => {
console.log(res);
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = { title, upvote, score, comments, created };
let postList = [];
postList.push(allPosts);
return postList;
});
console.log({"posts": posts});
return {"posts": posts};
});