使用Javascript或JQuery将数据插入JSON对象

时间:2018-03-03 05:38:26

标签: javascript jquery

最初我的变量是空的。

var data = [];

插入记录后应该是,

data = [
  { "date" : "2013-01-01", "open" : 45 },
  { "date" : "2013-02-01", "open" : 50 }
];

将新属性插入现有数据

data = [
  { "date" : "2013-01-01", "open" : 45 , "close": 49},
  { "date" : "2013-02-01", "open" : 50 , "close": 60}
];

我们如何使用JavaScript或J Query处理这两个场景?

2 个答案:

答案 0 :(得分:0)

这很简单。找到下面的代码段。

第一种情况,

data.push({ "date" : "2013-01-01", "open" : 45 },
          { "date" : "2013-02-01", "open" : 50 })

/* Data is 
   [{ "date" : "2013-01-01", "open" : 45 },
    {"date" : "2013-02-01", "open" : 50 }] */

第二种情况,

data = data.map(item => {item.close='30';return item})
/* Data is 
   [ { date: '2013-01-01', open: 45, close: '30' },
     { date: '2013-02-01', open: 50, close: '30' } ] */

答案 1 :(得分:0)

你也可以使用$ .each

    /**
     * @SWG\Post(
     *   tags={"pet"},
     *   path="/pet",
     *   summary="Create a pet",
     *   description="Create a pet",
     *   operationId="CreatePet",
     *   consumes={"application/json"},
     *   produces={"application/json"},
     *   @SWG\Parameter(
     *       name="pet",
     *           required=true,
     *           in="body",
     *           description="Pet object to be created",
     *       @SWG\Schema(
     *           @SWG\Property(property="pet",ref="#/definitions/Pet")
     *       ),
     *        example={
     *            "data": {
     *            "api_token": "ffdca087b7f97117330824ceea948a99",
     *            "id": "1",
     *            "email": "joe@doe.com",
     *            "first_name": "Joe",
     *            "last_name": "Doe"
     *            }
     *        }
     *   )