【问题标题】:Dynamically render objects in JSON在 JSON 中动态渲染对象
【发布时间】:2020-06-10 12:21:04
【问题描述】:

鉴于此 javascript 文件:

locations: {
"0": {
  name: "Paris",
  lat: "48.866666670",
  lng: "2.333333333",
  color: "default",
  description: "default",
  url: "default"
},
"1": {
  name: "Tokyo",
  lat: "35.666666670",
  lng: "139.750000000",
  color: "default",
  description: "default",
  url: "default"
},
"3": {
  name: "New York",
  lat: "40.71",
  lng: "-74.0059731",
  description: "default",
  color: "default",
  url: "default",
  size: "default"
},
"4": {
  name: "Miami",
  lat: "25.76",
  lng: "-80.19",
  description: "default",
  color: "blue",
  url: "default",
  size: "default"
},
  "5": {
  name: "Los Angeles",
  lat: "34.0522",
  lng: "-118.2437",
  description: "<h5 style='color:blue;font-weight:900;'>Aircraft Carrier:</h5><p>American Airlines</p>",
  color: "blue",
  url: "default",
  size: "default"
},
   "6": {
  name: "Robinson Helicopter R44",
  lat: "25.7090",
  lng: "-80.4381",
  description: "<h5 style='color:blue;font-weight:900;'>Aircraft Carrier:</h5><p style='font-size:.9rem'>American Airlines</p>",
  color: "blue",
  url: "default",
  size: "default"
},
  "7": {
  name: "Robinson Helicopter R44",
  lat: "40.4839361",
  lng: "-3.5679515",
  description: "<h5 style='color:blue;font-weight:900;'>Aircraft Carrier:</h5><p style='font-size:.9rem'>American Airlines</p>",
  color: "blue",
  url: "default",
  size: "default"
},

这些是交互式地图的城市/位置。城市的 JSON 将在地图上生成一个图钉。现在这是静态的。是否可以使用来自某个端点的 fetch 或 axios 请求动态创建这些 JSON 对象?

所以最后的文件应该是这样的:

locations: function() {
      fetch('https://www.podhurst.com/wp-json/wp/v2/aviation_map/')
        .then(res=> res.forEach((item,i)=>{
          "${i}": {
          name: "${item.acf.carrier}",
                lat: "${item.acf.latitude}",
                lng: "${item.acf.longitude}",
                color: "default",
                description: "$item.acf.description",
                url: "default"
          } })
         )},

【问题讨论】:

  • 你会如何渲染你的孩子?通过单击父对象,然后调用具有该 ID(父)的端点?
  • 不确定渲染子对象是什么意思,但@izambl 解决方案将其展平为数组。
  • @EugenSunic 因此,端点将为您提供所有信息,例如名称经度和纬度。最终结果需要像 "index": {name: "${fromEndPoint}",lat: "${fromEndPoint}"} 这样返回

标签: javascript json axios fetch


【解决方案1】:

您可以将内部对象转换为数组,这样它们会更容易渲染

const response = {"4": {...}, "5": {...}};

const cities = Object.keys(response).map((city) => response[city]);

【讨论】:

    【解决方案2】:

    这样的?

    fetch('https://www.podhurst.com/wp-json/wp/v2/aviation_map/')
        .then(res=>res.json())
        .then(res=>console.log({ ...res }))
    

    【讨论】:

    • 收到语法错误:SyntaxError: missing form parameter
    • 我不确定详细说明
    • 如果您将该代码复制并粘贴到控制台中,它将起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多