Javascript需要使用更多嵌套数据来推送或更新json对象

时间:2017-03-16 07:49:21

标签: javascript jquery json

我想将更多嵌套对象数据添加到现有对象

目前JSON对象数组(不确定我说的是正确的)如下所示:

var orderDetails = [{
  "utilityType": "Electric",
  "firstName": "ROBERT",
  "lastName": "GUERRERO",
  "utilityList": [{
        "name": "CPE",
        "type": "Electric",
        "ldcCode": "CPE",
        "accountNumberTypeName": "ESI ID"
  }],
  "program": [{
        "programId": 2090
  }]
}];

但是,我需要使用Javascript修改此JSON对象数据到append

所以我试图创建一个新的嵌套JSON对象,然后将push创建到现有的json对象数组中?

  var newOrder = [{
      "program": {
          "accountNumberType": {
              "accountNumberTypeName": "ESI ID"
         },
      "programId": 2090
   },
 }];


   orderDetails.push(orderDetails.program.accountNumberType.accountNumberTypeName = newOrder);

最终出现错误

  1. 是否可以更新现有的JSON对象?
  2. push会工作吗?
  3. 我的小提琴https://jsfiddle.net/j6L4s9mg/

    我基本上希望END RESULT看起来像这样:

    var orderDetails = [{
      "utilityType": "Electric",
      "firstName": "ROBERT",
      "lastName": "GUERRERO",
      "utilityList": [{
        "name": "CPE",
        "type": "Electric",
        "ldcCode": "CPE",
        "accountNumberTypeName": "ESI ID"
      }],
      "program": [{
         "accountNumberType": {
            "accountNumberTypeName": "ESI ID"
        },
        "programId": 2090
      }]
    }];
    

2 个答案:

答案 0 :(得分:0)

只需制作

orderDetails[0].program = newOrder[0].program;

check this fiddle

答案 1 :(得分:0)

Push会正常工作但orderDetails本身就是一个数组。所以首先迭代orderDetails数组,然后像这样推送代码

orderDetails.program.push(newOrder.program);

如果orderDetails是

var orderDetails = {
 "utilityType": "Electric",
 "firstName": "ROBERT",
 "lastName": "GUERRERO",
 "utilityList": [{
 "name": "CPE",
 "type": "Electric",
 "ldcCode": "CPE",
 "accountNumberTypeName": "ESI ID"
 }],
 "program": [{
 "programId": 2090
 }]
};

newOrder也是一个数组,所以再次迭代它然后推送。对于演示,我将它们都保留为对象而不是数组。只需输入循环语句,您就可以得到所需内容。 :)

工作演示在这里 - https://jsfiddle.net/vishalsrinivasan/5eLxj2bq/