Home > Blockchain >  Use function argument for key in returned object
Use function argument for key in returned object

Time:10-08

I have a very simple block of code:

function toObj(i){
    return {
        i: i
    };
}

numObj=s=>s.map(toObj)

When I pass an array of numbers to numObj, I expect the key and the value to match the argument that was passed in. For example, I would expect the following result:

numObj([1, 2, 3, 4]) => [{1: 1}, {2: 2}, {3: 3}, {4: 4}]

instead, I get this:

numObj([1, 2, 3, 4]) => [{i: 1}, {i: 2}, {i: 3}, {i: 4}]

How can I set the key of the returned object to be the argument that was passed in?

CodePudding user response:

Use computed property names to create the key from a value:

const toObj = i => ({ [i]: i })

const numObj = arr => arr.map(toObj)

const result = numObj([1, 2, 3, 4])

console.log(result)

  • Related