从JSON对象KEYS创建字符串 - Vanilla JavaScript或lodash

时间:2016-05-04 18:33:10

标签: javascript arrays json underscore.js lodash

需要一些帮助。

我有一个json对象,我想用对象的键创建一个字符串数组。

json对象

{
    "FEATURES": {
        "APP_DASHBOARD": {
            "MENU_TITLE": "Dashboard",
            "HEAD_TITLE": "Dashboard",
            "HEAD_DESC": "Welcome to briteplan"
        },
        "APP_TEAM": {
            "MENU_TITLE": "Teams",
            "HEAD_TITLE": "Teams",
            "HEAD_DESC": "",
            "TOOL_TIPS": {
                "TEAM_REFRESH": "Refresh teams",
                "TEAM_ADD": "Add new team",
                "TEAM_EDIT": "Edit team",
                "TEAM_REMOVE": "Remove team",
                "MEMBER_REMOVE" : "Remove team member",
                "MEMBER_LEAD" : "Team lead",
                "AVL_MEMBERS_REFRESH" : "Refresh available members"
            },
            "CONTENT": {
                "TEAMS_TITLE": "Teams",
                "MEMBERS_TITLE": "Members",
                "AVL_MEMBERS_TITLE": "Available team members"
            }
        }
    },
    "GENERAL": {
        "SEARCH_PLACEHOLDER": "Search ..."
    }
}

我想生成一个如下所示的数组:

var myArray = [
'FEATURES.APP_TEAM.MENU_TITLE',
'FEATURES.APP_TEAM.HEAD_TITLE',
'FEATURES.APP_TEAM.HEAD_DESC',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REFRESH',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_ADD',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_EDIT',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REMOVE',
];

并非所有价值都包含在内,但我认为您会获得理念。最重要的是我知道我在对象中有“FEATURES”,我将知道功能名称“APP_TEAM”,但我不知道该功能中的嵌套级别。

希望有人能帮助我。

1 个答案:

答案 0 :(得分:1)

递归:

function getKeys (o) {
  var keys = [];
  for (var prop in o) {
    if(o.hasOwnProperty(prop)) {
      if(typeof o[prop] === 'object') {
        getKeys(o[prop]).forEach(function (nestedProp) {
          keys.push(prop + '.' + nestedProp);
        });
      }
      else {
        keys.push(prop);
      }
    }
  }
  return keys;
}

在上面的对象上,返回:

[
  "FEATURES.APP_DASHBOARD.MENU_TITLE",
  "FEATURES.APP_DASHBOARD.HEAD_TITLE",
  "FEATURES.APP_DASHBOARD.HEAD_DESC",
  "FEATURES.APP_TEAM.MENU_TITLE",
  "FEATURES.APP_TEAM.HEAD_TITLE",
  "FEATURES.APP_TEAM.HEAD_DESC",
  "FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REFRESH",
  "FEATURES.APP_TEAM.TOOL_TIPS.TEAM_ADD",
  "FEATURES.APP_TEAM.TOOL_TIPS.TEAM_EDIT",
  "FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REMOVE",
  "FEATURES.APP_TEAM.TOOL_TIPS.MEMBER_REMOVE",
  "FEATURES.APP_TEAM.TOOL_TIPS.MEMBER_LEAD",
  "FEATURES.APP_TEAM.TOOL_TIPS.AVL_MEMBERS_REFRESH",
  "FEATURES.APP_TEAM.CONTENT.TEAMS_TITLE",
  "FEATURES.APP_TEAM.CONTENT.MEMBERS_TITLE",
  "FEATURES.APP_TEAM.CONTENT.AVL_MEMBERS_TITLE",
  "GENERAL.SEARCH_PLACEHOLDER"
]