Necesito crear un objeto de una estructura JSON. Estoy confundido sobre cómo hacer el recursivo de la estructura.

Esta es mi muestra de estructura JSON

{
        "dynamic.title": "Lorem Ipsum title",
        "dynamic.main_section.header.title": "Lorem Ipsum main section header title ",
        "dynamic.main_section.body.collection.first.title": "Lorem Ipsum main section  body collection first title",
        "dynamic.main_section.body.collection.first.description": "Lorem Ipsum main section  body collection first description",
        "dynamic.main_section.body.collection.first.id": "Lorem Ipsum main section  body collection first id",
        "dynamic.main_section.body.collection.first.child.first.title": "Lorem Ipsum main section  body collection first of first child title ",
        "dynamic.main_section.body.collection.first.child.first.id": "Lorem Ipsum main section  body collection first of first child id ",
        "dynamic.main_section.body.collection.first.child.first.url": "https://loremipsum/1",
        "dynamic.main_section.body.collection.first.child.first.names.first": "John Doe",
        "dynamic.main_section.body.collection.first.child.first.names.second": "Jane Doe",
        "dynamic.main_section.body.collection.second.title": "Lorem Ipsum main section  body collection second title",
        "dynamic.main_section.body.collection.second.description": "Lorem Ipsum main section  body collection second description",
        "dynamic.main_section.body.collection.second.id": "Lorem Ipsum main section  body collection second id",
        "dynamic.main_section.body.collection.second.child.first.title": "Lorem Ipsum main section  body collection second of first child title ",
        "dynamic.main_section.body.collection.second.child.first.id": "Lorem Ipsum main section  body collection second of first child id ",
        "dynamic.main_section.body.collection.second.child.first.url": "https://loremipsum/2",
        "dynamic.main_section.body.collection.second.child.second.title": "Lorem Ipsum main section  body collection second of second child title ",
        "dynamic.main_section.body.collection.second.child.second.id": "Lorem Ipsum main section  body collection second of second child id ",
        "dynamic.main_section.body.collection.second.child.second.url": "https://loremipsum/3"
    }

Lo que necesito formato es algo así.

{
        "dynamic": {
            "title": "Lorem Ipsum title",
            "main_section": {
                "header": {
                    "title": "Lorem Ipsum main section header title "
                },
                "body": {
                    "collection": [
                        {
                            "title": "Lorem Ipsum main section  body collection first title",
                            "description": "Lorem Ipsum main section  body collection first description",
                            "id": "Lorem Ipsum main section  body collection first id",
                            "child": [
                                {
                                    "title": "Lorem Ipsum main section  body collection first of first child title ",
                                    "id": "Lorem Ipsum main section  body collection first of first child id ",
                                    "url": "https://loremipsum/1",
                                    "names": ["John Doe", "Jane Doe"]
                                }
                            ]
                        },
                        {
                            "title": "Lorem Ipsum main section  body collection second title",
                            "description": "Lorem Ipsum main section  body collection second description",
                            "id": "Lorem Ipsum main section  body collection second id",
                            "child": [
                                {
                                    "title": "Lorem Ipsum main section  body collection second of first child title ",
                                    "id": "Lorem Ipsum main section  body collection second of first child id ",
                                    "url": "https://loremipsum/2"
                                },
                                {
                                    "title": "Lorem Ipsum main section  body collection second of second child title ",
                                    "id": "Lorem Ipsum main section  body collection second of second child id ",
                                    "url": "https://loremipsum/3"
                                }
                            ]
                        }
                    ]
                }
            }
        }
    }

Si la llave lateral izquierda consiste en el primer segundo, entonces será una matriz, pero si existe más de una propiedad, será un objeto o, de lo contrario, podría ser una matriz.

¿Cómo podría lograr esto en JS?

1
dev 8 jun. 2021 a las 21:01

2 respuestas

La mejor respuesta

Debe reemplazar los números a los índices y verificar las teclas para tener objetos o matrices.

const
    setValue = (object, path, value) => {
        const
            indices = { first: 0, second: 1 },
            keys = path.replace(new RegExp(Object.keys(indices).join('|'), 'g'), k => indices[k]).split('.'),
            last = keys.pop();

        keys
            .reduce((o, k, i, kk) => o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}, object)
            [last] = value;
            
        return object;
    },
    data = { "dynamic.title": "Lorem Ipsum title", "dynamic.main_section.header.title": "Lorem Ipsum main section header title ", "dynamic.main_section.body.collection.first.title": "Lorem Ipsum main section  body collection first title", "dynamic.main_section.body.collection.first.description": "Lorem Ipsum main section  body collection first description", "dynamic.main_section.body.collection.first.id": "Lorem Ipsum main section  body collection first id", "dynamic.main_section.body.collection.first.child.first.title": "Lorem Ipsum main section  body collection first of first child title ", "dynamic.main_section.body.collection.first.child.first.id": "Lorem Ipsum main section  body collection first of first child id ", "dynamic.main_section.body.collection.first.child.first.url": "https://loremipsum/1", "dynamic.main_section.body.collection.first.child.first.names.first": "John Doe", "dynamic.main_section.body.collection.first.child.first.names.second": "Jane Doe", "dynamic.main_section.body.collection.second.title": "Lorem Ipsum main section  body collection second title", "dynamic.main_section.body.collection.second.description": "Lorem Ipsum main section  body collection second description", "dynamic.main_section.body.collection.second.id": "Lorem Ipsum main section  body collection second id", "dynamic.main_section.body.collection.second.child.first.title": "Lorem Ipsum main section  body collection second of first child title ", "dynamic.main_section.body.collection.second.child.first.id": "Lorem Ipsum main section  body collection second of first child id ", "dynamic.main_section.body.collection.second.child.first.url": "https://loremipsum/2", "dynamic.main_section.body.collection.second.child.second.title": "Lorem Ipsum main section  body collection second of second child title ", "dynamic.main_section.body.collection.second.child.second.id": "Lorem Ipsum main section  body collection second of second child id ", "dynamic.main_section.body.collection.second.child.second.url": "https://loremipsum/3" },
    result = Object
        .entries(data)
        .reduce((r, [k, v]) => setValue(r, k, v), {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
2
Nina Scholz 8 jun. 2021 a las 18:19

Le muestro la forma de transformar los datos para que continúe con él e incluso automatícelo si es necesario;

let data = {
        "dynamic.title": "Lorem Ipsum title",
        "dynamic.main_section.header.title": "Lorem Ipsum main section header title ",
        "dynamic.main_section.body.collection.first.title": "Lorem Ipsum main section  body collection first title"
    }
    
dataTrans = {}
//data["dynamic.title"]
dataTrans.dynamic = {}
dataTrans.dynamic.title = data["dynamic.title"]
//data["dynamic.main_section.header.title"]
dataTrans.dynamic.main_section = {} 
dataTrans.dynamic.main_section.header = {}
dataTrans.dynamic.main_section.header.title = data["dynamic.main_section.header.title"]
dataTrans.dynamic.main_section.body = {} 
dataTrans.dynamic.main_section.body.collection = []
dataTrans.dynamic.main_section.body.collection[0] = {}
dataTrans.dynamic.main_section.body.collection[0].title = data["dynamic.main_section.body.collection.first.title"]

console.log(dataTrans)
0
Hamada 8 jun. 2021 a las 18:52