Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 배열 안 중첩 객체 값 합계 구하기

JavaScript에서는 map()forEach() 같은 배열 메서드를 활용하면 JSON처럼 깊게 중첩된 객체 구조 안의 숫자 값을 손쉽게 합산할 수 있습니다. 아래 예제는 배열에 중첩된 객체들의 특정 값을 모두 더하는 전체 코드입니다.

예제

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
    body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    .result {
        font-size: 18px;
        font-weight: 500;
        color: rebeccapurple;
    }
</style>
</head>
<body>
<h1>Sum of nested object values in Array</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to sum the nested object values of json array
</h3>
<script>
    let json = {
        storeData: [
        {
            items: [
            {
                itemID: 12,
                cost: {
                    costNum: 100,
                },
            },
            {
                itemID: 22,
                cost: {
                    costNum: 250,
                },
            },
            {
                itemID: 19,
                cost: {
                    costNum: 350,
                },
            },
            ],
        },
],
};
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
    let sum = 0;
    json.storeData.map((ele) => ({
        itemPrice: ele.items.forEach((item) => {
            sum += item.cost.costNum;
        }),
    }));
    resEle.innerHTML += "Total CostNum = " + sum + "<br>";
    });
</script>
</body>
</html>

코드 동작 방식

  • 데이터 구조: json 객체는 storeData 배열을 포함하며, 각 요소는 items 배열을, 그리고 각 아이템은 cost 객체 안의 costNum 값을 가지고 있습니다.
  • 합산 로직: 버튼을 클릭하면 map() 메서드가 storeData 배열을 순회하고, 내부의 forEach()가 각 아이템의 cost.costNum 값을 sum 변수에 누적합니다.
  • 결과 출력: 계산된 총합은 innerHTML을 통해 .result 영역에 표시됩니다.

출력 결과

위 코드를 실행하면 다음과 같은 화면이 나타납니다.

JavaScript로 배열 안 중첩 객체 값 합계 구하기

'CLICK HERE' 버튼을 클릭하면 −

JavaScript로 배열 안 중첩 객체 값 합계 구하기