0

How do i get only the obj keys i want, in a array of objects?

I have an array of keys and an array of objects.

let myKeys = ['first_name', 'last_name']

let myArray = [
{
 id: 1,
 fist_name: 'John',
 last_name: 'Paul',
 age: 22,
 city: 'New York'
},
{
 id: 1,
 fist_name: 'John',
 last_name: 'Paul',
 age: 22,
 city: 'New York'
},
{
 id: 1,
 fist_name: 'John',
 last_name: 'Paul',
 age: 22,
 city: 'New York'
},
]

How can i turn myArray into a new array based on 'myKeys'? Like below:

[
{
 first_name: 'John',
 last_name: 'Paul'
},
{
 first_name: 'John',
 last_name: 'Paul'
},
{
 first_name: 'John',
 last_name: 'Paul'
},
{
 first_name: 'John',
 last_name: 'Paul'
},
]
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
phdev
  • 17
  • 5
  • Does this answer your question? [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – Emile Bergeron Jul 05 '21 at 03:20

3 Answers3

1

You can use Array#map and Object.fromEntries.

let myKeys = ['first_name', 'last_name'];
let myArray=[{id:1,first_name:"John",last_name:"Paul",age:22,city:"New York"},{id:1,first_name:"John",last_name:"Paul",age:22,city:"New York"},{id:1,first_name:"John",last_name:"Paul",age:22,city:"New York"}];
let res = myArray.map(x => Object.fromEntries(myKeys.map(k => [k, x[k]])));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use map and reduce to achieve the result.

const result = myArray.map((obj) => {
  return myKeys.reduce((acc, curr) => {
    acc[curr] = obj[curr];
    return acc;
  }, {});
});

let myKeys = ["first_name", "last_name"];

let myArray = [{
    id: 1,
    first_name: "John",
    last_name: "Paul",
    age: 22,
    city: "New York",
  },
  {
    id: 1,
    first_name: "John",
    last_name: "Paul",
    age: 22,
    city: "New York",
  },
  {
    id: 1,
    first_name: "John",
    last_name: "Paul",
    age: 22,
    city: "New York",
  },
];

const result = myArray.map((obj) => {
  return myKeys.reduce((acc, curr) => {
    acc[curr] = obj[curr];
    return acc;
  }, {});
});

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

if you are not running on strict mode...

function reduceProp(objects, pops){
     let template = {};
     props.forEach((prop)=>{template[prop]="";}));
     Object.seal(template);
     return objects.map(object=>Object.assign( template, object));
}
Karthikeyan
  • 406
  • 3
  • 14