Search code examples
javascriptobjectecmascript-6object-literalshorthand

Does JavaScript have an object literal shorthand which automatically assigns to a property a value which is a string of the property name?


I understand that in ES2015+, instead of writing:

let myObject = { a: "a", b: "b", c: "c" };

I can use object shorthand to write the following:

let a = "a";
let b = "b";
let c = "c";

let myObject = { a, b, c };
console.log(myObject);

But that doesn't resemble the shorthand I am looking for.

Is there an approach in which I can declare an object literal without first defining variables and the properties of that object literal will be automatically assigned values which are stringified versions of the object's property names?

I.e. I write something similar to this:

let myObject = { a, b, c };

and it automatically resolves as:

let myObject = { a: "a", b: "b", c: "c" };

Or is that kind of shorter shorthand simply not possible?


Some background to this question:

My use-case is accepting both values and name-value pairs from users. The latter is straightforward enough. In the case of the former, I don't wish to make the user jump through the hoop of adding a name and then an identical value where one would suffice.


Solution

  • There is no syntax that would understand {a, b, c} when none of these a, b and c are defined variables. Moreover, it would not give a clue about the data types of these values, so in case of strings, you would need string values, not (undefined) variable references.

    From comments, it seems you get user input in the form of a string, which would include a series of pairs and single values.

    Here is a function that would parse such a string:

    const toObject = str =>
        Object.fromEntries(
            str.split(" ")
               .map(pair => pair.split("^"))
               .map(([k, v]) => [k, v??k])
        );
    
    let s = "name^John male height^185cm";
    let obj = toObject(s);
    console.log(obj);