0

In other words; how can I convert

// an array of length >= 3
let myArray = returnOfSomeParametricFunction(); // assuming repeating rhs removes dryness

let myObj = { staticKeyName: myArray[1], anotherStaticKeyName: myArray[2] };

to a single liner. Perhaps something like:

let myObj = returnOfSomeParametricFunction().reduce(arr=> { staticKeyName: arr[1], anotherStaticKeyName: arr[2] };
9
  • 1
    Note that array indices start at 0, not 1. Commented May 6, 2020 at 16:58
  • 2
    People really need to get over "single liner"s... Commented May 6, 2020 at 16:59
  • 1
    Like (a => ({ staticKeyName: a[1], anotherStaticKeyName: a[2] }))(returnOfSomeParametricFunction())? Commented May 6, 2020 at 17:03
  • 1
    @HereticMonkey But they're not trying to make variables named staticKeyName and anotherStaticKeyName. Those are intended to be property names Commented May 6, 2020 at 17:12
  • 1
    So more like Destructure array to object property keys then? Commented May 6, 2020 at 17:14

1 Answer 1

1

In this case, if I needed to do it in one line and not introduce a new variable in the same scope as myObj, and I didn't care about readability, I'd use an arrow function like this:

let myObj = (a => ({ staticKeyName: a[1], anotherStaticKeyName: a[2] }))(
  returnOfSomeParametricFunction());

You can verify that myObj has the properties of the right types. For example, given

declare function returnOfSomeParametricFunction(): [Date, number, string];

Then myObj would have type:

/*
let myObj: {
    staticKeyName: number;
    anotherStaticKeyName: string;
}
*/

Okay, hope that helps; good luck!

Playground link to code

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

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.