Search code examples
javascriptarraystypescriptecmascript-6destructuring

Can I declare an array of values that are nested inside a collection of objects without writing a loop?


Maybe a spread operator or destructuring instead? Instead of writing this function and calling it with the collection to create an array

function namesArray(group) {
        let names = [];
        group.values.forEach( (value) => {
            names.push(value.name);
        });
        return names;
    }

names: Array<string> = namesArray(group);

I want to do something like this:

names: Array<string> = group.values[....].value.name;

with the ellipsis representing some kind of operator.


Solution

  • You're looking for map():

    const names = group.values.map(v => v.name);