简体   繁体   中英

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

records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}]

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: "jack55@xyz.com", last_name: "Aston"}, {id: 232, email: "roy@xy.com", last_name: "Dillon"}, {id: 233, email: "jacy@x.com", last_name: "Wilson"}]

 const records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}] const fields = ['id', 'email', 'last_name'] console.log(records.map(i=>Object.fromEntries(fields.map(f=>[f, i[f]]))))

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

You can use Object.prototype.entries to 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: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}] 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM