JavaScript - fromEntries() method

revision:


Category : object

The Object.fromEntries() static method transforms a list of key-value pairs into an object.

Syntax :

        Object.fromEntries(iterable)
    

Parameters:

iterable : required. An iterable, such as an Array or Map, containing a list of objects. Each object should have two properties:

0 : a string or symbol representing the property key.
1 : the property value.

Examples:

        const entries = new Map([
            ['foo', 'bar'],
            ['baz', 42]
        ]);
        const obj = Object.fromEntries(entries);
        console.log(obj);
        // Expected output: Object { foo: "bar", baz: 42 }

    

Practical examples

example: converting a map to an object.

code:
                    <div>
                        <p id="from-1"></p>
                    
                    </div>
                    <script>
                        const map = new Map([
                            ["foo", "bar"],
                            ["baz", 42],
                        ]);
                        const obj = Object.fromEntries(map);
                        console.log(obj); // { foo: "bar", baz: 42 }
                        document.getElementById("from-1").innerHTML = "object : " + JSON.stringify(obj);
                    </script>
                

example: converting an array to an object

code:
                    <div>
                        <p id="from-2"></p>
                    </div>
                    <script>
                        const arr = [
                            ["0", "a"],
                            ["1", "b"],
                            ["2", "c"],
                        ];
                        const object = Object.fromEntries(arr);
                        console.log(object); // { 0: "a", 1: "b", 2: "c" }
                        document.getElementById("from-2").innerHTML = "object : " + JSON.stringify(object);
                    </script>
                

example: object transformations

code:
                    <div>
                        <p id="from-3"></p>
                        <p id="from-4"></p>
                    </div>
                    <script>
                        const object1 = { a: 1, b: 2, c: 3 };
                        document.getElementById("from-3").innerHTML = "object 1 : " + JSON.stringify(object1);
                        const object2 = Object.fromEntries(
                            Object.entries(object1).map(([key, val]) => [key, val * 2]),
                        );
                        console.log(object2);
                        // { a: 2, b: 4, c: 6 }
                        document.getElementById("from-4").innerHTML = "object 1 : " + JSON.stringify(object2);
                    </script>