将数组中的数据分区并存储在变量中 (Javascript / JSON)

Partition data from array and store in variable (Javascript / JSON)

我有一个要求,我需要对传入数据进行分区,如下例所示:

//required payload

{
"campaign_id": "",
"recipient": {
    "first_name": "",
    "last_name": "",
    "company": "",
    "email": "",
    "address_1": "",
    "city": "",
    "state": "",
    "postal_code": "",
    "identifier": ""
}
}

但是,我的问题是当前发布到我的端点的有效负载如下所示:

//entire payload

"body": {
"info": [
{
"campaign_id": "",
"recipient": {
    "first_name": "",
    "last_name": "",
    "company": "",
    "email": "",
    "address_1": "",
    "city": "",
    "state": "",
    "postal_code": "",
    "identifier": ""
}
}
],
"otherArray": [],
"otherString": "",
"otherString2": ""
}
} 

我想做的是从第二个例子中提取我第一个例子中需要的数据,然后将它存储在一个变量中。类似下面的内容:

var requiredPayload = {"campaign_id": "", "recipient": {}};

如何将 campaign_id + 收件人对象放入单个变量中?

我们应该能够将信息数组的第一个元素分配给 requiredPayload 变量,如下所示:

 
   const payload = {
    "body": {
        "info": [
            {
                "campaign_id": "",
                "recipient": {
                    "first_name": "",
                    "last_name": "",
                    "company": "",
                    "email": "",
                    "address_1": "",
                    "city": "",
                    "state": "",
                    "postal_code": "",
                    "identifier": ""
                }
            }
        ],
        "otherArray": [],
        "otherString": "",
        "otherString2": ""
    }
};

var requiredPayload = payload.body.info[0];
console.log("requiredPayload:", requiredPayload);

试试这个:

    var data={"body": {
        "info": [
        {
        "campaign_id": "",
        "recipient": {
            "first_name": "",
            "last_name": "",
            "company": "",
            "email": "",
            "address_1": "",
            "city": "",
            "state": "",
            "postal_code": "",
            "identifier": ""
        }
        }
        ],
        "otherArray": [],
        "otherString": "",
        "otherString2": ""
        }
        };
    console.log(data.body.info[0]); //data is variable name
var info_data=data.body.info[0];

如果信息有多个 campaign_id 那么试试这个

$.each(data.body.info, function (indexInArray, valueOfElement) { 
    console.log(data.body.info[indexInArray]);
});