0

For example, if I begin with this array in JavaScript:

Array Persons:
[0]: { Name: Henry, Age: 20, Height: 68, Weight: 150}
[1]: { Name: Tom, Age: 34, Height: 69, Weight: 140}
[2]: { Name: Jerry, Age: 45 Height: 63, Weight: 175}

and then I have the array of the fields I want to pull

Array Filter:
[0]: "Name"
[1]: "Weight"

How can I filter the first array using the second to then return only those fields stated in the second array?

Expected return:

Array Persons2:
[0]: { Name: Henry, Weight: 150}
[1]: { Name: Tom, Weight: 140}
[2]: { Name: Jerry, Weight: 175}

Thanks! Please let me know if I can clarify anything.

Taylor
  • 81
  • 10

1 Answers1

1

You can use Array#map and Array#reduce methods as follows:

const persons = [{ Name: "Henry", Age: 20, Height: 68, Weight: 150},{ Name: "Tom", Age: 34, Height: 69, Weight: 140},{ Name: "Jerry", Age: 45, Height: 63, Weight: 175}],

filter = ["Name","Weight"],

persons2 = persons.map(
  person => filter.reduce(
    (acc, prop) => ({...acc, [prop]: person[prop]}),
  {})
);

console.log( persons2 );
PeterKA
  • 24,158
  • 5
  • 26
  • 48