phdev
phdev

Reputation: 17

How can i get a new Array with only the object keys i want from an Array of Objects?

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'
},
]

Upvotes: 0

Views: 71

Answers (3)

Karthikeyan
Karthikeyan

Reputation: 414

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));
}

Upvotes: 1

DecPK
DecPK

Reputation: 25408

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);

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89264

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);

Upvotes: 1

Related Questions