Search code examples
node.jsnwjs

Object.entries is not a function in NWJS 0.36.3 (Node 11.10.1)


I am trying to create a function that swaps 'keys' with 'values' in an Object. For some reason, I'm getting a TypeError: object.entries is not a function. What am I missing or doing wrong here?

Object.defineProperty(Object.prototype, 'swapKeysValues', {
    value: function() {
        let obj = {};
        this.entries().forEach(([key, value]) => {
            obj[value] = key;
        });
        return obj;
    }
});

Further testing reveals:

let foo = { a: 1, b: 2, c: 3 }
typeof foo // "object"
foo instanceof Object // true
foo.entries // undefined
foo.entries() // Uncaught TypeError: foo.entries is not a function

Update:

So what I learned is that objects (i.e. let foo = { a: 1 }) do not inherit the .entries, .keys, or .values functions as properties, and I must access those functions by calling Object.entries(foo) as pointed out by tehhowch / SylvainF. Working code:

Object.defineProperty(Object.prototype, 'swapKeysValues', {
    value: function() {
        let obj = {};
        Object.entries(this).forEach(([key, value]) => {
            obj[value] = key;
        });
        return obj;
    }
});

// Example
let foo = { a: 1, b: 2, c: 3 }
foo.swapKeysValues()

// Output
{1: "a", 2: "b", 3: "c"}

Thank you tehhowch / SylvainF!


Solution

  • Like @tehhowch says in the comments, the syntax is Object.entries(foo)

    You can see the MDn page: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/entries