romjan
romjan

Reputation: 55

loop through array of objects and get all object values as a single string

I have an array of object

 const arr = [
  { id: 1, value: "Apple" },
  { id: 1, value: "Orange" },
  { id: 1, value: "Pine Apple" },
  { id: 1, value: "Banana" },
];

I want to loop through this array and get all the fruit names as a single string every fruit will separated with comma. But don't know how to do that. Does anybody help me to do this?

Upvotes: 0

Views: 5242

Answers (2)

milan
milan

Reputation: 325

const fruitNames = arr.map(fruit => fruit.value).toString();

Upvotes: 0

Cuong Vu
Cuong Vu

Reputation: 3733

You can use map and join like this

const arr = [
  { id: 1, value: "Apple" },
  { id: 1, value: "Orange" },
  { id: 1, value: "Pine Apple" },
  { id: 1, value: "Banana" },
];
const result = arr.map(({ value }) => value).join(', ')
console.log(result)

Upvotes: 4

Related Questions