javascript - 从 JSON 字符串中提取嵌套的 <a> 元素

标签 javascript arrays node.js recursion

我正在尝试查找 JSON 字符串中的所有“a”键并将它们保存在数组中。由于它们可能嵌套在不同的级别,因此我使用递归来遍历每个键的子级,以详尽地列出所有“a”键。但是,我无法专注于递归子 Node 并将任何找到的“a”键附加到返回的数组。如有任何帮助,我们将不胜感激。

遍历JSON字符串的函数:

searchForKeys = (keyValue, obj) => {

  let arrayOfKeys = [];

  if (obj instanceof Array) {
    obj.forEach((item, index) => {

     if(typeof(item) === 'object' && Object.keys(item)[index] === keyValue) {
        console.log('pushing found item to return array');
        arrayOfKeys.push(...item);
        console.log(arrayOfKeys);
     } 
    });
  }
  else if (typeof(obj) === 'object') {
    if (Object.keys(obj).length > 0) {
      let itemName;
      for(let i = 0; i < Object.keys(obj).length; i++) {
        itemName = Object.keys(obj)[i];
        if (itemName === keyValue) {
          console.log('pushing found item to return array');
          arrayOfKeys.push(obj[itemName]);
        }
      }
      console.log('arrayOfKeys.length:', arrayOfKeys.length);
      arrayOfKeys.push(searchForKeys(keyValue, obj[itemName]));
  }
  return arrayOfKeys;
  }
};

let returnedArray = searchForKeys("a", dummyJSON);

console.log("array content:\n", [...returnedArray]); 
console.log("array length", returnedArray.length);

预期结果是返回数组,其中包含 JSON 对象中的所有四个“a”键。

源数据:

const dummyJSON = {
  "a": {
    "@attributes": {
      "href": "/URL/2021.html?q=link+value",
      "title": "Lautsprecher",
      "class": "catfilter-list-link",
      "data-gtm-event": "filter.click",
      "data-gtm-payload": "{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}",
      "data-metric-click": "mainsearch-catfilter-click"
    },
    "#text": "Lautsprecher"
  },
  "ul": {
    "@attributes": {
      "class": "catfilter-list"
    },
    "#text": [],
    "li": [
      {
        "@attributes": {
          "class": "catfilter-list-item"
        },
        "#text": [
          "",
          ""
        ],
        "a": {
          "@attributes": {
            "href": "/URL/8412.html?q=link+value",
            "title": "Handy-Ladegeräte",
            "class": "catfilter-list-link",
            "data-gtm-event": "filter.click",
            "data-gtm-payload": "{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}",
            "data-metric-click": "mainsearch-catfilter-click"
          },
          "#text": "Handy-Ladegeräte"
        }
      },
      {
        "@attributes": {
          "class": "catfilter-list-item"
        },
        "#text": [
          "",
          ""
        ],
        "a": {
          "@attributes": {
            "href": "/URL/26136.html?q=link+value",
            "title": "Kabellose Ladegeräte",
            "class": "catfilter-list-link",
            "data-gtm-event": "filter.click",
            "data-gtm-payload": "{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}",
            "data-metric-click": "mainsearch-catfilter-click"
          },
          "#text": "Kabellose Ladegeräte"
        }
      },
      {
        "@attributes": {
          "class": "catfilter-list-item"
        },
        "a": {
          "@attributes": {
            "href": "/URL/2021.html?q=link+value",
            "title": "Lautsprecher",
            "class": "catfilter-list-link",
            "data-gtm-event": "filter.click",
            "data-gtm-payload": "{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}",
            "data-metric-click": "mainsearch-catfilter-click"
          },
          "#text": "Lautsprecher"
        },
        "#text": [
          "",
          ""
        ],
        "a": {
          "@attributes": {
            "href": "/URL/2021.html?q=link+value",
            "title": "Lautsprecher",
            "class": "catfilter-list-link",
            "data-gtm-event": "filter.click",
            "data-gtm-payload": "{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}",
            "data-metric-click": "mainsearch-catfilter-click"
          },
          "#text": "Lautsprecher"
        }
      }
    ]
  }
};

最佳答案

对于 JSON 字符串,JSON.parse reviver parameter可以使用:

var arr = [], json = JSON.stringify({"a":{"@attributes":{"href":"/URL/2021.html?q=link+value","title":"Lautsprecher","class":"catfilter-list-link","data-gtm-event":"filter.click","data-gtm-payload":"{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}","data-metric-click":"mainsearch-catfilter-click"},"#text":"Lautsprecher"},"ul":{"@attributes":{"class":"catfilter-list"},"#text":[],"li":[{"@attributes":{"class":"catfilter-list-item"},"#text":["",""],"a":{"@attributes":{"href":"/URL/8412.html?q=link+value","title":"Handy-Ladegeräte","class":"catfilter-list-link","data-gtm-event":"filter.click","data-gtm-payload":"{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}","data-metric-click":"mainsearch-catfilter-click"},"#text":"Handy-Ladegeräte"}},{"@attributes":{"class":"catfilter-list-item"},"#text":["",""],"a":{"@attributes":{"href":"/URL/26136.html?q=link+value","title":"Kabellose Ladegeräte","class":"catfilter-list-link","data-gtm-event":"filter.click","data-gtm-payload":"{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}","data-metric-click":"mainsearch-catfilter-click"},"#text":"Kabellose Ladegeräte"}},{"@attributes":{"class":"catfilter-list-item"},"a":{"@attributes":{"href":"/URL/2021.html?q=link+value","title":"Lautsprecher","class":"catfilter-list-link","data-gtm-event":"filter.click","data-gtm-payload":"{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}","data-metric-click":"mainsearch-catfilter-click"},"#text":"Lautsprecher"},"#text":["",""],"a":{"@attributes":{"href":"/URL/2021.html?q=link+value","title":"Lautsprecher","class":"catfilter-list-link","data-gtm-event":"filter.click","data-gtm-payload":"{\"event_category\":\"mainsearch\",\"event_action\":\"quickfilter.click\",\"event_label\":\"quickfilter\",\"position\":\"1\",\"location\":\"headline\"}","data-metric-click":"mainsearch-catfilter-click"},"#text":"Lautsprecher"}}]}})

JSON.parse(json, (key, val) => key == 'a' ? arr.push(val) : val)

console.log( arr )

关于javascript - 从 JSON 字符串中提取嵌套的 <a> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56827823/

相关文章:

javascript - 如何创建和组织配置并注册 grunt 任务

sql - PostgreSQL:意外的数组元素

parent 的javascript parent

javascript - 在 Angular 2 中获取数组的副本而不影响原始数组

javascript - Handlebars.js 打印对象不起作用

c - 在c中将数据从文件加载到数组

arrays - 访问数组时使用分隔符

javascript - Promise 函数需要使用 return 吗?

javascript - 响应式导航不起作用(React)

javascript - Backbone.Marionette + Rails 应用程序在表单提交后重定向。为什么?