数组转对象

作者: 椋椋夜色 | 来源:发表于2019-06-25 08:51 被阅读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>

    相关文章

      网友评论

        本文标题:数组转对象

        本文链接:https://www.haomeiwen.com/subject/gxpzqctx.html