【问题标题】:Modify Dynamic Json structure to flat keys and value将 Dynamic Json 结构修改为平面键和值
【发布时间】:2021-10-29 07:19:11
【问题描述】:

我想将不同的 json 结构更改为平面结构,以便在 html 上轻松呈现。所以我在数据中有嵌套,有时我得到键和值,有时只是值。有什么简单的方法吗?

这是我拥有的一些 json 示例:

         {
            "title": "example glossary",
            "GlossDiv": {
                "title": "S",
                "GlossList": {
                    "GlossEntry": {
                        "ID": "SGML",
                        "SortAs": "SGML",
                        "GlossTerm": "Standard Generalized Markup Language",
                        "Acronym": "SGML",
                        "Abbrev": "ISO 8879:1986",
                        "GlossDef": {
                            "para": "A meta-markup language, used to create markup languages such as DocBook.",
                            "GlossSeeAlso": ["GML", "XML"]
                        },
                        "GlossSee": "markup"
                    }
                }
            }
        }

这是我想要得到的东西

        "glossary": {
            "title": "example glossary",
            "GlossDivTitle": "S",
            "GlossDivGlossListGlossEntryID": "SGML",
            "GlossDivGlossListGlossEntrySortAs": "SGML",
            "GlossDivGlossListGlossEntryGlossTerm": "Standard Generalized Markup Language",
            "GlossDivGlossListGlossEntryAcronym": "SGML",
            "GlossDivGlossListGlossEntryAbbrev": "ISO 8879:1986",
            "GlossDivGlossListGlossEntryGlossDefPara": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossDivGlossListGlossEntryGlossDefGlossSeeAlso": "GML, XML",
            "GlossDivGlossListGlossEntryGlossSee": "markup",
        }

我正在使用 sencha js,想法是在 html 中呈现任何类型的 json,类似这样。

        tpl: new Ext.XTemplate(
            '<table border="1" cellpadding="10" cellspacing="0">',
            '<tpl foreach=".">',
            '<tr>',
            '<td>{$}</td>',
            '<td>{.}</td>',
            '</tr>',
            '</tpl>',
            '</table>'
            , {
                complied: true
            }
        )

【问题讨论】:

  • 这是一对一模型的完美示例;)那么您无需做任何事情

标签: javascript arrays json extjs


【解决方案1】:

递归是一种解决方案:

更新:

const flattenedKeys = (json) => {

  // Container for the keys
  const flattenedObj = {};

  const traverse = (obj, currentPath = '') => {

    // Traverse all the properties
    Object.entries(obj).forEach(([key, value]) => {

      const newPath = currentPath + key;

      // If obj[key] is an array
      if (Array.isArray(value)) {

        value.forEach(item => {
          traverse(item, newPath)
        });

        return;
      }


      // If obj[key] traverse recursively nested properties
      if (typeof value === 'object') return traverse(value, newPath);

      // If obj[key] is not an object or an array
      flattenedObj[newPath] = value;

    });

  }

  // Traverse recursively the whole object
  traverse(json);

  return flattenedObj;

}

【讨论】:

  • 我认为这涵盖了我的大部分结构,但如果我有类似的东西仍然没有涵盖。 "functionalName": [{ "text": "Test", "language": "eng" }],
  • 这应该在使用Array.isArray(obj[item])来检查值是否是数组。
  • 没错,我刚刚编辑了你的情况(当数组可以包含对象时)
  • 我还需要一些更正。例如这个 "countryOfOrigin": ["191"] 将导致 countryOfOrigin0 - 1, countryOfOrigin1 - 9, countryOfOrigin2 - 1
  • 你有没有在数组中有一个数组的场景,比如([[[]]])?
【解决方案2】:

如果你想扁平化你需要做递归循环的对象

下面是一个简单的示例,只是为了说明它是如何工作的,它不使用递归。

// You data to be flatten
var obj = { ... }
var data = {}
Object.keys(obj).forEach(function (item) {
  // Check for value type of object
  if(typeof obj[item] == 'object') {
    // Check if array
    if(Array.isArray(obj[item])) {
      // Append the value
      data[item] = obj[item];
    } else {
      // Must loop to this object
      // You can recursive function
      var nestObj = obj[item];
      Object.keys(nestObj).forEach(nest => {
        // Append to the data
        // This time with nested object,
        // We have to merge the parents key and the nested key
        data[item+nest] = nestObj[nest]
      })
    }
  } else {
    // Append non object values
    data[item] = obj[item];
  }
})

【讨论】:

  • 我尝试了,但这不是我需要的结果,仍然没有变平
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 1970-01-01
  • 2015-02-01
  • 2020-07-06
  • 2020-11-29
  • 1970-01-01
相关资源
最近更新 更多