从数组中分割数据并存储在变量中(Javascript / JSON)

问题描述 投票:0回答:2

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

//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
+
recipient
对象放入单个变量中?

javascript json stringify
2个回答
2
投票

试试这个:

    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]);
});

1
投票

我们应该能够将 info 数组的第一个元素分配给 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);

© www.soinside.com 2019 - 2024. All rights reserved.