0

Is it possible to do this:

const foo = [1, 2];
const bar = {
    a: foo[0],
    b: foo[1],
    c: 'something else not in array'
};

as a single statement, avoiding the need to declare foo?

As example, the array could be the result of

"1, 2".split(', ')

and you want to avoid the interim variable declaration, using "1" and "2" as the values for two of the properties (and potentially not the only properties) in a new object.

I can imagine something like this, though neither is valid for various reasons:

const bar { a, b, c: 'something else not in array' } = [1, 2];

or

const bar { a:[0], b:[1], c: 'something else not in array' } = [1, 2];

EDIT: The closest I've found, without using an IIFE, is

Object.assign({c: 'something else not in array'}, [1, 2])

which has a negative in that rather than properties named 'a' and 'b', you get properties named '0' and '1':

{0: 1, 1: 2, c: "something else not in array"}
BrianFreud
  • 5,614
  • 5
  • 28
  • 47
  • 1
    You can smoosh pretty much anything into a single line, but that won't make it readable. If you don't want to create intermediate variables, there's no special syntax sugar for that, the best you'll be able to to is iterate over an array of key names associated with the array values – CertainPerformance Apr 20 '19 at 07:08
  • That's why I said "avoiding the need to declare foo". You can do [a, b] = [b, a], but I'm wondering about c {a, b} = [a, b]. – BrianFreud Apr 20 '19 at 07:11
  • 1
    You have to define the `a`, `b` somewhere like: `const [a, b] = "1,2".split(','); const bar = { a, b, c: "something else"}` If you're not too particular about the key names, `{ ...array, c: "something else"}` creates numerical keys – adiga Apr 20 '19 at 07:13
  • Yes, it's that defining somewhere else I'm wondering if we can somehow now avoid. The latter might be partially there... I know we can rename arguments while using destructuring with objects, but could the destructured array's [0], [1], etc also be renamed? – BrianFreud Apr 20 '19 at 07:20
  • There is no legitimate reason to avoid declaring variables though. You could write your code without any variables for sure, but that doesnt make it more readable. – Jonas Wilms Apr 20 '19 at 07:22
  • Jonas, the same could be said for [a,b] = [b,a], and just as wrongly. – BrianFreud Apr 20 '19 at 07:23
  • 1
    Are the names *a* and *b* fixed, or are they also dynamically determined? – trincot Apr 20 '19 at 07:24
  • Yes, a and b can be assumed to be static property names for bar. – BrianFreud Apr 20 '19 at 07:27

2 Answers2

1

Yes, using an IIFE:

 const bar = (([a, b]) => ({ a, b, c: "other props" }))([1, 2]);
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
0

If it concerns exactly two properties/values, then reduce can also work:

const bar = [1, 2].reduce((a, b) => ({ a, b, c: "other"}));
trincot
  • 211,288
  • 25
  • 175
  • 211