重命名数组的嵌套键

时间:2016-02-10 12:01:17

标签: javascript angularjs

我需要更改嵌套数组的值才能使用插件

https://github.com/khan4019/tree-grid-directive

我的JSON看起来像这样:

[{"Id":13,"Name":"sadas","Users":[],"Managers":[],"Departments":[{"Id":14,"Name":"hgjghjghjg","Users":[],"Managers":[],"Departments":[{"Id":16,"Name":"kjk","Users":[],"Managers":[],"Departments":[{"Id":17,"Name":"vcxv","Users":[],"Managers":[],"Departments":[]}]}]},{"Id":15,"Name":"p[op[","Users":[],"Managers":[],"Departments":[]}]}]

要使用角度插件,需要重命名每个键Departments to children,然后从键中删除""

我尝试使用Json.stringify,并在默认字符串

中替换
var objToSend = JSON.stringify(response.Departments);
var str = objToSend.replace("\"Departments\":", "\"children\":");
$rootScope.tree_data = str;

但它对我不起作用,它只是更改数组的第一个键,但不是嵌套并返回

[{"Id":13,"Name":"sadas","Users":[],"Managers":[],"children":[{"Id":14,"Name":"hgjghjghjg","Users":[],"Managers":[],"Departments":[{"Id":16,"Name":"kjk","Users":[],"Managers":[],"Departments":[{"Id":17,"Name":"vcxv","Users":[],"Managers":[],"Departments":[]}]}]},{"Id":15,"Name":"p[op[","Users":[],"Managers":[],"Departments":[]}]}]

1 个答案:

答案 0 :(得分:4)

您的替换方法不起作用,因为替换只会更改第一次出现。但是你可以使用正则表达式来完成它。

或(在我看来)更好的是你可以使用array.map

进行嵌套map

像这样的东西

function rename (obj) {
  for(var prop in obj) {

    if (Array.isArray(obj[prop])) {
        obj[prop] = obj[prop].map(rename);
    }

    if (prop === 'Departments') {
      obj.children = obj[prop];
      delete obj[prop];
    }
  }

    return obj;
};

var y = x.map(rename);

然而,这只会递归检查数组。不是嵌套的对象属性。但是看看你的数据,它似乎只是数组。

例如,这对于这样的结构不起作用。

var data = {
  "Id": 17,
  "Name": "vcxv",
  "Users": [],
  "Managers": [],
  "Departments": {
    "Id": 18,
    "Name": "trollol",
    "Users": [],
    "Managers": [],
    "Departments": {}
  }
};

演示小提琴:https://jsfiddle.net/f90uh9ou/

编辑:更新,你也可以使用Object.keys来获取数组中的对象键。不太确定这里是否有任何好处,但for in甚至可能会影响性能。 Object.keys在函数组合和方法链等方面更有用。

但是这里有一个更新的小提琴。 https://jsfiddle.net/f90uh9ou/1/