如何添加名称已作为另一个属性存在的JSON项

How to add a JSON item whose name already existed as another attribute?

本文关键字:属性 另一个 存在 JSON 何添加 添加      更新时间:2023-09-26

我正在尝试创建这个:

var a = {
"requestM" : {
    "task" : "list",
    "listRequest" : {
        "checkedEntryType" : "GLOBAL",
        "targetList" : {
            "maxResult" : "2",
            "status" : "OPEN",
            "entryType" : "CALL"
        },
        "targetList" : {
            "maxResult" : "3",
            "status" : "CLOSED",
            "entryType" : "CALL"
        },
        "targetList" : {
            "maxResult" : "2",
            "status" : "OPEN",
            "entryType" : "TODO"
        },
        "targetList" : {
            "maxResult" : "2",
            "status" : "CLOSED",
            "entryType" : "TODO"
        }
    }
}

}

targetList没有嵌套在数组中,但它会重复。现在我尝试创建这样的消息:

var reqJson = {
        "requestM" : {
            "task" : "list",
            "listRequest" : {
                "checkedEntryType" : checkedEntryType
            }
        }
    };
    reqJson.requestM.listRequest.targetList={
        "maxResult" : 10,
        "status" : "OPEN",
        "entryType" : "CALL"
    };
    reqJson.requestM.listRequest.targetList={
        "maxResult" : 10,
        "status" : "OPEN",
        "entryType" : "TODO"
    };

但是,第二个targetList将取代第一个targetList。如何避免这种情况?谢谢

键对于对象必须是唯一的。将其值设为数组。一旦您从JSON转换为JavaScript对象,就可以将数据推送到上面。

"listRequest" : {
    "checkedEntryType" : "GLOBAL",
    "targetList" : [
    {
        "maxResult" : "2",
        "status" : "OPEN",
        "entryType" : "CALL"
    },
    {
        "maxResult" : "3",
        "status" : "CLOSED",
        "entryType" : "CALL"
    }
    ]

我认为这是不可能的,因为在json对象中

var o = 
{
 "p1": value1,
 "p2": value2 
}

p1和p2被认为是对象的属性,因此重复的属性被覆盖。相反,尝试使用阵列

targetList : [ { "maxResult" : "2",
        "status" : "OPEN",
        "entryType" : "CALL"}, { "maxResult" : "3",
        "status" : "CLOSED",
        "entryType" : "CALL"}, {..} ]