在另一个obj中添加一些obj字段

时间:2015-08-07 00:21:53

标签: javascript object merge

在我的示例中,OBJ(scope.fields)始终是默认值,OBJ(scope.grupos)将仅在OBJ(scope.fields)模型字段中添加。

但是下面的这个函数不能,我也尝试了underscore.js和lodash.js失败了。他保留了OBJ键(scope.grupos)。

只能插入模型字段。

  function merge(obj1, obj2) {
    var result = {};
    for (i in obj1) {
      result[i] = obj1[i];
      if ((i in obj2) && (typeof obj1[i] === "object") && (i !== null)) {
        result[i] = merge(obj1[i], obj2[i]);
      }
    }
    for (i in obj2) {
      if (i in result) { //conflict
        continue;
      }
      result[i] = obj2[i];
    }
    return result;
  }

JSON数据:

  //GRUPOS CRIADOS SEGUIR ESTE JSON
  $scope.fields = [{
    "fields": [{
      "type": "input",
      "title": "Nome do projeto",
      "key": "projeto-name",
      "obs": "Adicione aqui o nome do projeto."
    }],
    "id": "1",
    "posted": "2015-08-05T06:42:11.598Z",
    "title": "Projetos",
    "show": "posts"
  }, {
    "fields": [{
      "type": "checkbox"
    }, {
      "type": "checkbox"
    }],
    "id": "2",
    "posted": "2015-08-06T22:37:16.046 Z",
    "title": "Categorias dos Projetos",
    "show": "posts"
  }];




  // GRUPO DO POST
  $scope.grupo = [{
    "id": "1",
    "posted": "2015-08-05T06:42:11.598Z",
    "title": "Projetos",
    "show": "posts",
    "fields": [{
      "type": "input",
      "title": "Nome do projeto",
      "key": "projeto-name",
      "obs": "Adicione aqui o nome do projeto.",
      "model": "Projeto teste"
    }],
  }, {
    "id": "2",
    "posted": "2015-08-05T07:03:23.054 Z ",
    " title ": "Super teste ",
    "show ": " posts",
    "fields": [{
      "type": "input",
      "title": "Campo de texto simples",
      "key": "simples",
      "obs": "fdsdsdsdsdsd",
      "required": true,
      "model": "Agora é um super teste"
    }, {
      "type": "textarea",
      "title": "Campo de texto longo",
      "key": "longo",
      "obs": "dsfsdfsdfsdfsdf",
      "required": true,
      "model": "Superrrrrr testeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
    }],
  }, {
    "id": "3",
    "posted": "2015-08-06T22:37:16.046Z",
    "title": "Categorias dos Projetos",
    "show": "posts",
    "fields": [{
      "type": "checkbox ",
      "model": true
    }, {
      "type": "checkbox",
      "model": true
    }]

  }];

完美的世界:

  //GRUPOS CRIADOS SEGUIR ESTE JSON
  $scope.grupo = [{
    "fields": [{
      "type": "input",
      "title": "Nome do projeto",
      "key": "projeto-name",
      "obs": "Adicione aqui o nome do projeto."
      "model": "Projeto teste"

    }],
    "id": "1",
    "posted": "2015-08-05T06:42:11.598Z",
    "title": "Projetos",
    "show": "posts"
  }, {
    "fields": [{
      "type": "checkbox",
      "model": true
    }, {
      "type": "checkbox",
      "model": true
    }],
    "id": "2",
    "posted": "2015-08-06T22:37:16.046 Z",
    "title": "Categorias dos Projetos",
    "show": "posts"
  }];

http://plnkr.co/edit/S20jluwSyXncp74KyTn9?p=preview

0 个答案:

没有答案