Как мне взять элементы из массива и разместить их в правильном порядке? - PullRequest
1 голос
/ 03 марта 2020

, поэтому я не могу решить эту проблему. У меня есть следующие массивы:

var array1 = [
USA,
Georgia,
Atlanta
]

var array2 = [
USA,
New York
]

Это то, что я хочу:

{
    "counties": [
        {
            "name": "USA",
            "id": "1",
            "children": [
                {
                    "name": "Georgia",
                    "id": "1.1",
                    "parentId": "1",
                    "children": [
                        {
                            "name": "Atlanta",
                            "id": "1.1.1",
                            "parentId": "1.1"
                        }
                    ]
                },
                {
                    "name": "New York",
                    "id": "1.2",
                    "parentId": "1"
                }
            ]
        }
    ]
}

Хитрость заключается в том, чтобы не иметь дубликатов, если есть дубликаты на одном уровне, они должны быть объединены в одно и иметь обоих детей под. Как США в примере.

1 Ответ

1 голос
/ 03 марта 2020

У меня есть transform методы. Передайте любое количество массивов в параметрах:

Демо:

const array1 = [
    'USA',
    'Georgia',
    'Atlanta'
]

const array2 = [
    'USA',
    'New York'
]



const transform = (...arrays) => {
    const result = [];

    arrays.forEach(array => {
        let node = result;
        let parentID = ''

        array.forEach(item => {

            const current = node.find(c => c.name === item);

            if(current){
                node = current.children
            }else{
                const newNode = {
                    name: item,
                    children: [],
                    id: parentID === '' ? (node.length+1) + '' : parentID + '.'  + (node.length+1),
                    parentID
                };

                parentID = newNode.id;
                node.push(newNode);
                node = newNode.children
            }

        })
    })

    return {counties: result}
}

const result = transform(array1, array2);

console.log(result);

// {
//     "counties": [
//         {
//             "name": "USA",
//             "id": "1",
//             "parentID": "",
//             "children": [
//                 {
//                     "name": "Georgia",
//                     "id": "1.1",
//                     "parentID": "1",
//                     "children": [
//                         {
//                             "name": "Atlanta",
//                             "id": "1.1.1",
//                             "parentID": "1.1",
//                             "children": []
//                         }
//                     ]

//                 },
//                 {
//                     "name": "New York",
//                     "children": [],
//                     "id": "2",
//                     "parentID": ""
//                 }
//             ]

//         }
//     ]
// }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...