如何使用JavaScript在现有的json数组中添加键及其值

时间:2019-01-29 06:41:18

标签: javascript jquery

我需要使用Javascript在现有的json数组中添加键及其值。我在下面解释我的数组。

var finalOut=[
            {
                "location": "Jaipur",
                "nos_of_fos": 4,
                "login_id": [
                    "9619300332",
                    "9619300347"
                ],
                "total_remarks": 0,
                "total_disposition_code": {"PTP": 3,
                    "CB": 1,"TPT":4}
            },
            {
                "location": "BHILWARA,",
                "nos_of_fos": 1,
                "login_id": [
                    "9619300346"
                ],
                "total_remarks": 4,
                "total_disposition_code": {
                    "PTP": 3,
                    "CB": 1
                }
            },
            {
                "location": "AJMER",
                "nos_of_fos": 2,
                "login_id": [
                    "9619300357"
                ],
                "total_remarks": 0,
                "total_disposition_code": {}
            }
        ]

这里我需要total_disposition_code是否具有任何值,然后将其所有键和值添加到根对象中,并在下面给出预期的输出结果。

 var result=[
                {
                    "location": "Jaipur",
                    "nos_of_fos": 4,
                    "login_id": [
                        "9619300332",
                        "9619300347"
                    ],
                    "total_remarks": 0,
                    "PTP":3,
                    "CB":1,
                    "TPT":4
                },
                {
                    "location": "BHILWARA,",
                    "nos_of_fos": 1,
                    "login_id": [
                        "9619300346"
                    ],
                    "total_remarks": 4,
                    "PTP":3,
                    "CB":1,
                },
                {
                    "location": "AJMER",
                    "nos_of_fos": 2,
                    "login_id": [
                        "9619300357"
                    ],
                    "total_remarks": 0,
                }
            ]

我需要使用javascript的上述格式。我还尝试了以下代码。

for(var key in finalOut){
     finalOut[key]['total_disposition_code'][key]=
    //console.log(finalOut[key]);
}

2 个答案:

答案 0 :(得分:0)

您可以简单地使用spread语法,并执行以下操作:

const result = finalOut.map(object => {
  if (object['total_disposition_code']) {
    const mergedObject = {...object, ...object['total_disposition_code']}
    delete mergedObject['total_disposition_code']
    return mergedObject;
  }
}) 

答案 1 :(得分:0)

您可以使用ES6代码,它将返回您喜欢的对象

Find open running ports: C:\WINDOWS\system32>netstat -ano | findstr :Port number Example: netstat -ano | findstr :8761 kill ports based on PID(process ID) C:\WINDOWS\system32>taskkill /PID PIDNumber /F Example: taskkill /PID 3740 /F