js复习

数组转对象

2019-06-25  本文已影响0人  椋椋夜色

<!DOCTYPE html>
<html lang="zh-CN">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> 数组转对象 </title>

</head>

<body>
    <script>
        //对象转数组
        let arr = []
        let obj = {
            liang: "18",
            liang1: "16"
        }
        console.log('对象转数组前:', obj); // 对象转数组前: {liang: "18", liang1: "16"}
        for (let prop in obj) {
            arr.push({
                name: prop,
                age: obj[prop]
            })
        }
        console.log('对象转数组后:', JSON.stringify(arr, null, 2)); 
        // 对象转数组后: [ { "name": "liang","age": "18" }, {"name": "liang1", "age": "16" }]


        // 数组转对象
        let arr1 = [{
                name: 'liang2',
                ct: '18'
            },
            {
                name: 'liang3',
                ct: 16
            }
        ]
        console.log('数组转对象前:', arr1); // 数组转对象前: (2) [{name: "liang2", ct: "18"},{name: "liang3", ct: 16}]
        let obj1 = {}
        arr1.forEach(item => {
            obj1[item.name] = item.ct
        })
        console.log('数组转对象后:', JSON.stringify(obj1, null, 2)); // 数组转对象后: {"liang2": "18", "liang3": 16}
    </script>

</body>

</html>

上一篇下一篇

猜你喜欢

热点阅读