2

I'm trying to convert an array to an object (keyed by the first element).

foo = [1,2]

function convert_foo(foo) {
    return { foo[0]: foo[1] };
}

The following is not valid Javascript: Uncaught SyntaxError: Unexpected token [.

I've also tried:

function convert_foo(foo) {
    return ({ foo[0]: foo[1] });
}

EDIT:

It's possible this way, but I was wondering if there was a way to return it in one line.

function convert_foo(foo) {
    var obj = {}
    obj[foo[0]] = foo[1];
    return obj;
}

2 Answers 2

4

For dynamic keys (aka computed property names in ECMAScript 2015), you have to put the key in square brackets:

function convert_foo(foo) {
    return { [foo[0]]: foo[1] };
}

console.log(convert_foo([1, 2]));

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks I'll accept it. Is there a way to use this with map? i.e. foo_array.map(foo => { [foo[0]]: foo[1] })?
With map(), you mean mapping an array to an object with multiple properties?
I just found it. foo_array.map(foo => ({ [foo[0]]: foo[1] })). Wrapping the return ().
1

With the upcoming Object.fromEntries(), that is already supported on some browsers, you can also do something like this:

function convert_foo(foo)
{
    return Object.fromEntries([foo]);
}

console.log(convert_foo([1, 2]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.