从现有的 JSON 对象数组创建一个空的 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17003334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:50:42  来源:igfitidea点击:

Create a empty JSON object from an existing JSON object array

javascriptarraysjsonobjectangularjs

提问by user6123723

I have a JSON object with two arrays of an object x.

我有一个带有两个对象数组的 JSON 对象x

I'm using angularJS and I want to add/edit/delete objects in the JSON (just like the Angular TODO app example on angular.org).

我正在使用 angularJS,我想在 JSON 中添加/编辑/删除对象(就像 angular.org 上的 Angular TODO 应用程序示例)。

Is there a way to create a new empty (with the structure of xbut no values) JSON object of x, and simply push that to the above JSON object array?

有没有办法创建一个新的空(具有结构x但没有值)的 JSON 对象x,然后简单地将它推送到上面的 JSON 对象数组?

How do I go about creating an empty value JSON object of x?

我如何去创建一个空值 JSON 对象x

My Sample object x is (I nullified all the values) pasted below. So my JSON is just an array of these objects. In Angular, I want the user to fill out a form and hold the data in an empty object of this type and push it to the array. That's my goal.

我的示例对象 x 是(我取消了所有值)粘贴在下面。所以我的 JSON 只是这些对象的数组。在 Angular 中,我希望用户填写表单并将数据保存在这种类型的空对象中,然后将其推送到数组中。这就是我的目标。

Sample JSON

示例 JSON

      [{
        "id": null,
        "title": "",
        "date": {},
        "billPayerId": null,
        "notes": "Sample Notes",
        "billFinances": {
            "billPayerId": null,
            "billItemEntry": [
                {
                    "itemDescriptionId": 1,
                    "itemDescription": "",
                    "userIdAndLiableCost": [
                        {
                            "userId": null,
                            "liableCost": null
                        },
                        {
                            "userId": null,
                            "liableCost": null
                        }
                    ]
                },
                {
                    "itemDescriptionId": null,
                    "itemDescription": "",
                    "userIdAndLiableCost": [
                        {
                            "userId": null,
                            "liableCost": null
                        },
                        {
                            "userId": null,
                            "liableCost": null
                        }
                    ]
                }
            ],
            "billTotal": null
        },
        "groupId": null
    }];

回答by Matt Self

You can use an object literal to store whatever you want. It is just a bag of properties (i.e. name) and values. e.g. var order = {};

您可以使用对象字面量来存储您想要的任何内容。它只是一包属性(即名称)和值。例如var order = {};

Then an array literal could be used to hold the orders. e.g var orders = []; orders.push(order);But it would be just as easy to use another object literal with the id as a property.

然后可以使用数组文字来保存订单。 e.g var orders = []; orders.push(order);但是使用另一个带有 id 作为属性的对象字面量也同样容易。

But it seems like you want some sort of validation. Perhaps something to manage the order data and handle the validation, etc. Like so:

但似乎您想要某种验证。也许可以管理订单数据和处理验证等。像这样:

orderManager.dataStore = {
  _data: {},
  //_redundantData = [];  //could easily store in an array if id isn't unique
  get: function (id) {
    return this._data[id];
  },
  getAll: function () {
    return this._data;
  },
  set: function (id, order) {
    validateOrder(order);
    this._data[id] = order;
  },

  clear: function (id) {
    this._data[id] = undefined;
  },
  add: function (order) {
      validateOrder(order);
      this._data[order.id] = order;

  },
  assertNotNull: function (data, key) {
      if(data[key] == undefined) {
        throw new Error("Key Missing: " + key + " for " + data.name);
      }
  },
  validateOrder: function(order) {
    assertNotNull(order,"id");
    assertNotNull(order,"title");
    //etc
  },
  containsOrder: function (id) {
    for(var i=0;i<array.length;i++) {
        if(array[i].id === id) {
            return true;
        }
    }
    return false;
  }
};

回答by Justin L.

If I'm reading all of this right, I think you may be misunderstanding how Angular works. You don't have to create an empty object for Angular to use within a form. As long as your form's inputs use dot notation, it will generate the object for you as the user fills in the inputs with data.

如果我正确阅读了所有这些内容,我认为您可能误解了 Angular 的工作原理。您不必为 Angular 创建一个空对象以在表单中使用。只要您的表单输入使用点表示法,它就会在用户用数据填充输入时为您生成对象。

E.g.

例如

<form>
    <input type="text" ng-model="myForm.name">
    <input type="text" ng-model="myForm.email">
    <input type="text" ng-model="myForm.nickname">
</form>

Since we used the dot notation in the ng-modelattribute, it creates the object for us as the user fills out the form. The generated object would look like this after the inputs are completed:

由于我们在ng-model属性中使用了点符号,因此它会在用户填写表单时为我们创建对象。输入完成后,生成的对象将如下所示:

$scope.myForm = {
    name: 'Justin',
    email: '[email protected]',
    nickname: 'Cerebrl'
};

Now, normally once the user clicks save, you'd send the data to the server for persistence and you could then just empty the object (e.g. $scope.myForm = {};) to reset the form. But, for some reason, you want to build an array first, then send the whole thing to the server when fully complete (at least that's how I'm understanding it).

现在,通常一旦用户单击保存,您会将数据发送到服务器以进行持久化,然后您可以清空对象(例如$scope.myForm = {};)以重置表单。但是,出于某种原因,您想先构建一个数组,然后在完全完成后将整个内容发送到服务器(至少我是这样理解的)。

To do this, you have to get around the fact that Objectsand Arraysin JavaScript are reference types, so you can't push the object full of data to an array, and then empty the object to reset the form as that would then empty the object within the array as well, blowing your data store.

为此,您必须绕过JavaScript 中的ObjectsArrays是引用类型的事实,因此您不能将充满数据的对象推送到数组,然后清空该对象以重置表单,因为这会清空该对象也在阵列中,炸毁您的数据存储。

I would personally address this problem with Angular's object copy method (e.g. angular.copy(source);) seen here: http://docs.angularjs.org/api/angular.copyThis allows you to make a non-referenced copy of an object and use it without mutating the original object. So, within the "save function", you would have this:

我个人会使用 Angular 的对象复制方法(例如angular.copy(source);)来解决这个问题:http: //docs.angularjs.org/api/angular.copy这允许您制作对象的非引用副本并使用它而不会发生变异原始对象。因此,在“保存功能”中,您将拥有:

var myNewObj = angular.copy($scope.myForm);
myDataArray.push(myNewObj);
$scope.myForm = {};

That way, you've saved the completed form data, pushed it to the array and cleared the form's input data. Does this answer your question?

这样,您就保存了完成的表单数据,将其推送到数组并清除了表单的输入数据。这回答了你的问题了吗?