Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS – Convert JSON Array

I need help for simple question, to convert this:

{
    "data": [{
        "data_1": {
            "name": "name1",
            "value": "value1"
        },
        "data_2": {
            "name": "name2",
            "value": "value2"
        }
    }]
}

To this:

I need help for simple question, to convert this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "data": {
        "data_1": {
            "name": "name1",
            "value": "value1"
        },
        "data_2": {
            "name": "name2",
            "value": "value2"
        }
    }
}

Need to remove ‘[]’.
Thanks a lot!

>Solution :

Ideally you want to make a deep copy of those inner objects, and create a new object with them. There are many ways to do this but one of the easiest methods is to stringify them (ie the first element of the array), and then parse that string. That way new references are built, and changes to the original data won’t have an effect on the new data.

const data={data:[{data_1:{name:"name1",value:"value1"},data_2:{name:"name2",value:"value2"}}]};

// Stringify, and then parse the string
const copy = (o) => JSON.parse(JSON.stringify(o));

// Assemble the new object by copying the part
// for reuse
const out = { data: copy(data.data[0]) };

// Check that changes made to the original object
// are not reflected in the new object
data.data[0].data_1.name = 'bob';

console.log(out);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading