0

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'

2
  • That's a reduce, not a map. Commented Feb 9, 2019 at 17:23
  • do you like to update interface? Commented Feb 9, 2019 at 17:24

2 Answers 2

4

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);

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

1 Comment

wow thank you so much, this works great!!!! Acceptable in 8 minutes :-)
-1

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;
    }, "");

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.