Method to obtain specific key-value pairs in an array object
P粉604669414
P粉604669414 2024-01-16 11:23:03
0
2
374


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 do I get only "id", "email" and "last_name" from the record so that the data looks like this 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"}]


P粉604669414
P粉604669414

reply all(2)
P粉860897943
const newRecords=records.map(item=>{return {id,email,last_name}})
P粉057869348

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]]))))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!