You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript遍历指定JSON结构,提取标题、内容和URL?

遍历JSON获取标题、内容和URL的JavaScript方案

你已经通过JSON.parse(this.response)将响应内容转为了JavaScript对象,接下来只需要先取出posts对象,再遍历它的键值对就能拿到所有标题、内容和URL,以下是几种可行的实现方式:

方式一:嵌套使用Object.entries

const parsedData = JSON.parse(this.response);
// 提取posts对象
const posts = parsedData.posts;

// 遍历posts的键值对,键就是标题,值是包含内容和URL的对象
for (const [title, postInfo] of Object.entries(posts)) {
  console.log('标题:', title);
  console.log('内容:', postInfo.content);
  console.log('URL:', postInfo.url);
  console.log('---');
}

方式二:用Object.keys结合forEach

const parsedData = JSON.parse(this.response);
const posts = parsedData.posts;

// 获取所有标题(posts对象的键)
const postTitles = Object.keys(posts);
postTitles.forEach(title => {
  // 解构取出内容和URL
  const { content, url } = posts[title];
  console.log(`标题:${title}`);
  console.log(`内容:${content}`);
  console.log(`URL:${url}`);
  console.log('---');
});

方式三:for...in循环(需过滤原型属性)

const parsedData = JSON.parse(this.response);
const posts = parsedData.posts;

// 遍历posts的所有键
for (const title in posts) {
  // 确保只处理对象自身的属性,避免遍历到原型链上的属性
  if (posts.hasOwnProperty(title)) {
    const postInfo = posts[title];
    console.log('标题:', title);
    console.log('内容:', postInfo.content);
    console.log('URL:', postInfo.url);
    console.log('---');
  }
}

你可以根据实际需求替换console.log部分的代码,比如将这些数据渲染到页面DOM中。

内容的提问来源于stack exchange,提问作者Loek Lemmens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:50:28