如何在Javascript中将嵌套对象合并到父对象中?

时间:2014-12-18 02:49:32

标签: javascript angularjs object merge

我正在尝试在Angular.js中使用过滤器功能,但它不会对对象起作用。

如何使用Javascript将嵌套对象合并到其父对象中?

e.g。我想转此:

{
  "data" : [ {
    "character" : {
      "realm" : 1,
      "displayName" : "John",
    },
    "points" : 1388.0,
    "wins" : 84,
    "losses" : 31
  }, {
    "character" : {
      "realm" : 1,
      "displayName" : "Steven",
    },
    "points" : 1363.0,
    "wins" : 96,
    "losses" : 24
  }, {
    "character" : {
      "realm" : 1,
      "displayName" : "Mark",
    },
    "points" : 1322.0,
    "wins" : 154,
    "losses" : 43
  }
]}

进入这个:

{
  "data" : [ {
    "realm" : 1,
    "displayName" : "John",
    "points" : 1388.0,
    "wins" : 84,
    "losses" : 31
  }, {
    "realm" : 1,
    "displayName" : "Steven",
    "points" : 1363.0,
    "wins" : 96,
    "losses" : 24
  }, {
    "realm" : 1,
    "displayName" : "Mark",
    "points" : 1322.0,
    "wins" : 154,
    "losses" : 43
  }
]}

有人能帮助我吗?

3 个答案:

答案 0 :(得分:2)

您可以使用extendhttps://docs.angularjs.org/api/ng/function/angular.extend)循环和分配:

for (var i = 0; i < data.length; i++) {
    angular.extend(data[i], data[i].character) //move properties from character to the parent
    delete data[i].character; //delete the "character" key
}

答案 1 :(得分:1)

纯Javascript方法:

&#13;
&#13;
var source = {
  "data" : [ {
    "character" : { "realm" : 1, "displayName" : "John" },
    "points" : 1388.0,
    "wins" : 84,
    "losses" : 31
  }, {
    "character" : { "realm" : 1, "displayName" : "Steven" },
    "points" : 1363.0,
    "wins" : 96,
    "losses" : 24
  }, {
    "character" : { "realm" : 1, "displayName" : "Mark" },
    "points" : 1322.0,
    "wins" : 154,
    "losses" : 43
  }
]}

source.data.forEach(function(item) {
    var character = item.character;
    delete item.character;
    for(var prop in character) {
        item[prop] = character[prop];
    }
});

console.log(source);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用

var obj = {
  "data": [{
    "character": {
      "realm": 1,
      "displayName": "John",
    },
    "points": 1388.0,
    "wins": 84,
    "losses": 31
  }, {
    "character": {
      "realm": 1,
      "displayName": "Steven",
    },
    "points": 1363.0,
    "wins": 96,
    "losses": 24
  }, {
    "character": {
      "realm": 1,
      "displayName": "Mark",
    },
    "points": 1322.0,
    "wins": 154,
    "losses": 43
  }]
};
for (var key in obj.data) {
  obj.data[key].realm = obj.data[key].character.realm; // store the realm key to the obj
  obj.data[key].displayName = obj.data[key].character.displayName; // store the displayName key to the obj
  delete obj.data[key].character; // delete a character key

}