简体   繁体   English

遍历 javaScript 中的嵌套对象数组

[英]Iterate through a nested array of objects in javaScript

When I load my html page, I have this returned:当我加载我的 html 页面时,我得到了这个返回:

id: country url: http://data:8004/v1/entity/country name: countries description: All the countries in the world id: country url: http://data:8004/v1/entity/country name: countries 描述: 世界上所有国家

id: states url: http://data:8004/v1/entity/states name: states data description: A catalog of all data id: states url: http://data:8004/v1/entity/states 名称:states 数据描述:所有数据的目录

When I click on the link, I get something like this:当我点击链接时,我得到这样的东西:

id: edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e49
url:http://data:8004/v1/entity/county/edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e49
type: country, 
name: London, 
legal: [object Object]

It doesn't return the data in the Legal [{}].它不会返回 Legal [{}] 中的数据。

This is what the json looks like:这是 json 的样子:

[
    {
        "id": "edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e49",
        "url": "http://data:8004/v1/entity/county/edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e499",
        "type": "country",
        "name": "London",
        "legal": [
            {
                "type": "attribution",
                "link": "https://en.wikipedia.org/"
            }
        ]
    },

How can I loop through the nested array to access and retrieve legal[{}] ?如何遍历嵌套数组以访问和检索legal[{}] Also, when i click on a URL, it returns my results, and when I click on another one, it moves the previous results down and positions the new one on top without clearning the old one.此外,当我单击 URL 时,它会返回我的结果,而当我单击另一个时,它会向下移动先前的结果并将新结果放在顶部而不清除旧结果。 I tried using ```results.innerHTML=';" but it still didn't clear the dom before loading new results.我尝试使用 ```results.innerHTML=';" 但在加载新结果之前它仍然没有清除 dom。

This is my code:这是我的代码:


const createElement = (tag, ...content) => {
    const el = document.createElement(tag);
    el.append(...content);
    return el;
  };
  
  const setData = (entity) =>{
      console.log(JSON.stringify(entity))
      let entityProps = Object.keys(entity)
      console.log(entityProps)
  const dl = document.createElement('dl');

  entityProps.forEach(function(prop) {
 
    const pre_id =  document.createElement('pre');

    const dt_id =  document.createElement('dt');
    dt_id.textContent = prop;

    pre_id.appendChild(dt_id);
  
    const dd_id =  document.createElement('dd');
    

    if (prop == "url") {
        const link = document.createElement('a');
        link.textContent = entity[prop];
        link.setAttribute('href', '#')
        link.addEventListener('click',function(e) {
      console.log("I'm working!")
      console.log(e.target.innerHTML)
      RetrieveData(e.target.innerHTML)
  });
  dd_id.appendChild(link);

    } else {
        dd_id.textContent = entity[prop];

    }

    pre_id.appendChild(dd_id);
  
    dl.appendChild(pre_id);

    
  });



  return dl;
  
  }

    const results = document.getElementById("results");


function RetrieveData(url){
   
    fetch(url
    , {
        headers:{
      'x-data': '78shjjhsjja-95ff-a6c0396bd619.b77738aa-f798-4bb9-93c4-914c5c83608c',
      'x-access': 'access-data',
      
    },
})
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
  .then((data) => {
    results.append(
        ...data.flatMap((entry) => [
            setData((entry)),
          document.createElement("br"),
          document.createElement("br"),
        ])
      );
  })
  .catch(console.error);
}


const data=document.getElementById("data");

catalog.addEventListener("onclick",  RetrieveData(`http://data:8004/v1/entity/`));

You are setting the value of the properties that are not 'url' to be the value of the JS object. This is the relevant part of your code.您正在将不是“url”的属性的值设置为 JS object 的值。这是代码的相关部分。

 if (prop == "url") {
        const link = document.createElement('a');
        link.textContent = entity[prop];
        link.setAttribute('href', '#')
        link.addEventListener('click',function(e) {
      console.log("I'm working!")
      console.log(e.target.innerHTML)
      RetrieveData(e.target.innerHTML)
  });
  dd_id.appendChild(link);

    } else {
        dd_id.textContent = entity[prop];

    }

You have there to make an special case for legal too, then you have two options:你也必须在那里为法律做一个特例,然后你有两个选择:

  • To JSON.stringify the legal property JSON.stringify legal财产
  • To process the values inside of legal as you are doing with the countries处理 legal 内部的值,就像处理国家/地区一样

A simple implementation of the JSON.stringify solution: JSON.stringify解决方案的简单实现:

 if (prop == "url") {
        const link = document.createElement('a');
        link.textContent = entity[prop];
        link.setAttribute('href', '#')
        link.addEventListener('click',function(e) {
          console.log("I'm working!")
          console.log(e.target.innerHTML)
          RetrieveData(e.target.innerHTML)
        });
        dd_id.appendChild(link);

    } if (prop == "legal") {
        dd_id.textContent = JSON.stringify(entity[prop]);
    }else {
        dd_id.textContent = entity[prop];
    }

About not clearing your results it could be that you are always appending new elements but it isn't easy to follow without a testing environment.关于不清除结果,可能是因为您总是在添加新元素,但如果没有测试环境,则不容易遵循。

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

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