0

I get a JSON array in jquery and now I want to convert this array json data to specific JSON data. I use a arr.push to create this json. Now I want to change this format:

[
    {
        "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
        }
    }
]

Into this format:

{
    "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
    },
}

I have tried doing this:

arrayJsonModel.push({ question: arrayJson[0] })
2
  • 1
    We know what you want to do. But what have you tried? Commented May 6, 2019 at 6:41
  • arrayJsonModel.push({ question: arrayJson[0] }) i try this. Commented May 6, 2019 at 6:43

1 Answer 1

3

Use reduce and spreading:

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

Sign up to request clarification or add additional context in comments.

2 Comments

nice but how i use this { ...acc, ...curr } within <script> tag i face error
What error @UmarAsif? Press Run above, it's working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.