0

I have an array like this

const array = [{a: '1', b: '2'}, {a: '3', b: '4' }];

I want to join the only field into a string to have a result like this: '1, 3'

The join function of an array can only be used on the whole entry, not on fields of the object that is underneath. Is there a way to do this with standard functionality or do I have to use a for loop or a forEach?

1
  • you'll need a loop, I'd go for a .map Commented Jul 31, 2020 at 12:23

2 Answers 2

8

Before join you need map array

const array = [
    { a: '1', b: '2' },
    { a: '3', b: '4' },
];

const result = array.map(_ => _.a).join(', ');

console.log(result);

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

Comments

0

In order to perform this through For loop.

result = [];
const array = [{ a: '1', b: '2' }, { a: '3', b: '4' }];
array.forEach(elm => result.push(elm.a));
console.log(result.join(", "));
// 1, 3

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.