/**
 * @since Last modified: 2024/04/20 14:39:01
 * @function selectToArr
 * @description Convert the select node tree to an array of objects, in the format: [{node:'',label:'',value:''},{node:'',label:'',value:''}...].If you need to bring the id, pId, path and floor properties you need to use the "treeTools.addIdPath" method.
 * @param {HTMLElement} el - Node selector
 * @param {boolean} [replace=true] - Whether to use the label text as the value if there is no value attribute.
 * @returns {object[]}  - Returns the One- or two-dimensional tree array data.
 * @see {@link https://codepen.io/axui/pen/MWRwVxK|demo @ codepen}
 * @example
 * ax.selectToArr('#id');
 */
'use strict';
import getEl from "./getEl";
import treeTools from "./treeTools";
const selectToArr = (el, replace = true) => {
    let elem = getEl(el);
    if (!elem) {
        throw new Error(`No node, no access to data!`);
    }
    let getChild = () => {
        let data = [];
        [...elem.children].forEach(k => {
            data.push(getJson(k));
        });
        return data;
    }, getJson = (elem) => {
        let obj = { node: elem, ...treeTools.getValsFromAttrs(elem) }, label = elem.textContent.trim(), value = elem.hasAttribute('value') ? elem.getAttribute('value').trim() : '';
        if (elem.nodeName == 'OPTGROUP') {
            obj.label = elem.getAttribute('label').trim();
            obj.value = obj.label;
            obj.children = [];
            [...elem.children].forEach(item => {
                obj.children.push(getJson(item));
            });
        }
        else {
            obj.label = label ? label : value.trim();
            obj.value = replace ? (value ? value : obj.label) : value;
        }
        return obj;
    };
    return getChild();
};
export default selectToArr;
