Isaac
Isaac

Reputation: 12884

Array Destructuring + spread syntax with specific field only?

let arr = [{name: 'john', age:17}, {name: 'Doe', age: 21}];

//let dropDownHumanOptions = ['All', ...arr.name, 'Cancel']
//let dropDownHumanOptions = ['All', ...{arr.name}, 'Cancel']

//Expected: let dropDownHumanOptions = ['All', 'john', 'Doe', 'Cancel']

I'm wondering if there is any similar syntax where we can just extracting one of the field and combine in the middle of another array by using spread syntax?

Upvotes: 1

Views: 446

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

You need to spread the mapped names.

var array = [{name: 'john', age:17}, {name: 'Doe', age: 21}],
    dropDownHumanOptions = ['All', ...array.map(({ name }) => name), 'Cancel'];

console.log(dropDownHumanOptions);

Upvotes: 4

Related Questions