Reputation: 17
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
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
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
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