두 손끝의 창조자

json 요소 이동 본문

프로그래밍언어/Javascript

json 요소 이동

codinglog 2023. 11. 22. 17:42
function moveElementInJson(json, sourceId, destinationId, newIndex) {
    // 복제된 JSON 생성
    const updatedJson = JSON.parse(JSON.stringify(json));

    // 소스 요소 찾기
    const sourceElement = findElementById(updatedJson, sourceId);

    if (!sourceElement) {
        console.error('Source element not found.');
        return null;
    }

    // 소스 요소를 제거
    const removedElement = removeElementById(updatedJson, sourceId);

    // 대상 위치에 요소 삽입
    const destinationElement = findElementById(updatedJson, destinationId);
    if (destinationElement && destinationElement.children) {
        destinationElement.children.splice(newIndex, 0, removedElement);
    } else {
        console.error('Destination element not found or is not a directory.');
        return null;
    }

    return updatedJson;
}

function findElementById(json, id) {
    for (const element of json) {
        if (element.id === id) {
            return element;
        } else if (element.children) {
            const childElement = findElementById(element.children, id);
            if (childElement) {
                return childElement;
            }
        }
    }
    return null;
}

function removeElementById(json, id) {
    for (let i = 0; i < json.length; i++) {
        if (json[i].id === id) {
            return json.splice(i, 1)[0];
        } else if (json[i].children) {
            const removedElement = removeElementById(json[i].children, id);
            if (removedElement) {
                return removedElement;
            }
        }
    }
    return null;
}

// 사용 예시
const updatedJson = moveElementInJson(wsListData, '6551c3f72c4b8ee56604d2fa', '6551c5992c4b8ee56604d302', 2);
console.log(updatedJson);
반응형
Comments