0

I need to get an array of values for a particular key, from a sequence of objects inside an array using javascript.

Parent array

const a =[{employeeId: 033, field: "TAX", active: 1},
{employeeId: 035, field: "ACCOUNTING", active: 1},
 {employeeId: 035, field: "SALES", active: 1}];

Required output(array of values for the key named 'field')

["TAX","ACCOUNTING","SALES"]
Praveen G
  • 161
  • 1
  • 2
  • 8
  • ```const output = a.map(el=>el.field);``` Just a simple map() – ikhvjs Jul 12 '21 at 15:28
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Jul 12 '21 at 15:30

2 Answers2

1

You can use Array#map.

const a =[{employeeId: 033, field: "TAX", active: 1},
{employeeId: 035, field: "ACCOUNTING", active: 1},
 {employeeId: 035, field: "SALES", active: 1}];
const res = a.map(x => x.field);
// or a.map(({field})=>field);
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Please spend some with research if there isn't already a similar question, especially with such a common problem, instead of adding just another clone of an already available answer... – Andreas Jul 12 '21 at 15:31
1

array.map transforms an array for you.

const a =[{employeeId: 033, field: "TAX", active: 1},
{employeeId: 035, field: "ACCOUNTING", active: 1},
 {employeeId: 035, field: "SALES", active: 1}];
 
 console.log(a.map((e) => e.field));
Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33