javascript - JS return object by array index - Stack Overflow

I'm trying to convert an array to an object (keyed by the first element).foo = [1,2]function conve

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;
}

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;
}
Share Improve this question asked Jun 14, 2019 at 2:57 Alexander KleinhansAlexander Kleinhans 6,27813 gold badges66 silver badges119 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

For dynamic keys (aka puted 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]));

With the uping 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;}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745202000a4616381.html

相关推荐

  • javascript - JS return object by array index - Stack Overflow

    I'm trying to convert an array to an object (keyed by the first element).foo = [1,2]function conve

    5小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信