0

I would like to get the values of the attribute value in a new array. For the following example, the result would be: ["Plumbing", "Electrical", "Fencing"]

const arr = [
  { label: "Plumbing", value: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

I mean something like: newArray = currentArray forEach Get Value

Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36
benpalmer
  • 147
  • 1
  • 2
  • 13

2 Answers2

2

You can easily get the value of all label using map

const arr = [
  { label: "Plumbing", value: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

const result = arr.map((o) => o.value);
console.log(result);

You can also destructure to make it more succinct

const result = arr.map(({ value }) => value);

const arr = [
  { label: "Plumbing", value: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

const result = arr.map(({ value }) => value);
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

You can add your values to a new array using forEach like so :

const arr = [
  { value: "Plumbing", label: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

var newArr = []
arr.forEach(e => newArr.push(e.value))

console.log(newArr)

Or like @decpk said in comment you could simply use map() like so

const arr = [
  { value: "Plumbing", label: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

var newArr = arr.map(e => e.value)

console.log(newArr)
crg
  • 4,284
  • 2
  • 29
  • 57
  • 3
    why to use `forEach` when you have `map` that returns result in new array by default. – DecPK May 21 '21 at 23:28