如何将数组json数据转换为jquery中的特定json?

时间:2019-05-06 06:40:17

标签: javascript jquery arrays json object

我在jquery中得到一个JSON数组,现在我想将此数组json数据转换为特定的JSON数据。我使用arr.push创建了这个json。现在,我要更改格式:

[
    {
        "question": {
            "QuestionType": "QShortText",
            "Question": "What's your name?",
            "PlaceHolderText": "Placeholder",
            "IsNumericOnly": true,
            "CharacterLimit": 0,
            "IsRequired": true
        }
    },
    {
        "Paragraph": {
            "QuestionType": "QPargraphText",
            "Question": "789",
            "PlaceHolderText": "ytut",
            "CharacterLimit": 0,
            "IsRequired": true
        }
    }
]

转换为格式:

{
    "question": {
        "QuestionType": "QShortText",
        "Question": "What's your name?",
        "PlaceHolderText": "Placeholder",
        "IsNumericOnly": true,
        "CharacterLimit": 0,
        "IsRequired": true
    },      
    "Paragraph": {
        "QuestionType": "QPargraphText",
        "Question": "789",
        "PlaceHolderText": "ytut",
        "CharacterLimit": 0,
        "IsRequired": true
    },
}

我尝试这样做:

arrayJsonModel.push({ question: arrayJson[0] })

1 个答案:

答案 0 :(得分:3)

使用reduce并传播:

const data = [{"question":{"QuestionType":"QShortText","Question":"What's your name?","PlaceHolderText":"Placeholder","IsNumericOnly":true,"CharacterLimit":0,"IsRequired":true}},{"Paragraph":{"QuestionType":"QPargraphText","Question":"789","PlaceHolderText":"ytut","CharacterLimit":0,"IsRequired":true}}];
const output = data.reduce((acc, curr) => ({ ...acc, ...curr }), {});
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: auto; }