Home > Enterprise >  How to get certain key value pairs from an array of object
How to get certain key value pairs from an array of object

Time:11-23

records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "[email protected]"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "[email protected]"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "[email protected]"}]

fields = ['id', 'email', 'last_name']

How can I fetch only 'id', 'email', and 'last_name' from records just so that data looks as below in javascript?

new_records = [{id: 231, email: "[email protected]", last_name: "Aston"}, {id: 232, email: "[email protected]", last_name: "Dillon"}, {id: 233, email: "[email protected]", last_name: "Wilson"}]

CodePudding user response:

const records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "[email protected]"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "[email protected]"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "[email protected]"}]

const fields = ['id', 'email', 'last_name']

console.log(records.map(i=>Object.fromEntries(fields.map(f=>[f, i[f]]))))

CodePudding user response:

const newRecords=records.map(item=>{return {id,email,last_name}})

CodePudding user response:

You can use Object.prototype.entries to get change the object's key/value pairs into an array that contains the key and value.

 Object.entries({ id: 231, first_name: "Jack" });

 // [[id, 231], ["first_name", "Jack"]];

You can then use that to filter the key's value and return only these fields that you need. Then you can use Object.prototype.fromEntries to reverse the process and construct an object from key/value arrays.

Here's a quick example:

const records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "[email protected]"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "[email protected]"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "[email protected]"}]

const fields = ['id', 'email', 'last_name']

const newRecords = records.map((record) => Object.fromEntries(
    Object.entries(record).filter(([key, value]) => fields.includes(key) ? [key, value] : null))
);

console.log(newRecords);

  • Related