Sithys
Sithys

Reputation: 3803

map object.keys into string from array of objects

I have an array, this for example:

interface: [
    { _id: '1', name: 'Foo' },
    { _id: '2', name: 'bar },
    { _id: '3', name: 'boo}
]

i'd now like to map this to a single string ->

this.dataSource.data = data.data.map(item => ({
     interface: item.interfaces.name,
}));

so that the result inside the dataSource.data.interface looks like 'Foo, bar, boo'

Upvotes: 0

Views: 55

Answers (2)

ehutchllew
ehutchllew

Reputation: 958

Use Array.prototype.reduce:

const concatString = data.interface.reduce((acc, value, index, arr) => {
    const str = index !== arr.length - 1 ? `${value.name}, ` : value.name;
    return acc += str;
    }, "");

Upvotes: -1

Nina Scholz
Nina Scholz

Reputation: 386868

You could map the name property and join the array.

var data = { interface: [{ _id: '1', name: 'Foo' }, { _id: '2', name: 'bar' }, { _id: '3', name: 'boo' }]};

data.interface = data.interface.map(({ name }) => name).join(', ');

console.log(data);

Upvotes: 4

Related Questions