简体   繁体   中英

Filter an array of objects by keys in Javascript

I have gone through several similar posts about filtering the array based on the keys and tried implementing it as well but not able to get the correct answer. Here's my code -

const data = [{
  dnum: "061806",
  enddate: "2022-05-31",
  fnum: 0.7,
  role: "MP",
  startdate: "2022-01-13",
}, {
  dnum: "061806",
  enddate: "2022-05-31",
  fnum: 0.786,
  role: "MP",
  startdate: "2022-01-13",
}]

function copyObjectProps(source, keys) {
  let newObject = {}
  keys.forEach(function(key) {
    newObject[key] = source[key]
  })
  return newObject
}

let filteredObject = copyObjectProps(data, ['dnum', 'role', 'fnum'])

console.log(filteredObject)

I am getting the below result -

{
  dnum: undefined,
  role: undefined,
  fnum: undefined
}

But I am expecting it to be something like this -

[{
  dnum: "061806",
  fnum: 0.7,
  role: "MP",
}, {
  dnum: "061806",
  fnum: 0.786,
  role: "MP",
}]

Could anyone tell me what exactly I am doing wrong?

see this article

 const data = [{ dnum: "061806", enddate: "2022-05-31", fnum: 0.7, role: "MP", startdate: "2022-01-13", },{ dnum: "061806", enddate: "2022-05-31", fnum: 0.786, role: "MP", startdate: "2022-01-13", }] function selectProps(props){ return function(obj){ const newObj = {}; props.forEach(name =>{ newObj[name] = obj[name]; }); return newObj; } } let filteredObject1 = data.map(selectProps(['dnum', 'role','fnum'])) let filteredObject2 = data.map(selectProps(['dnum','fnum'])) console.log(filteredObject1) console.log(filteredObject2)

edit if want to change key names i did something like this

 const data = [{ dnum: "061806", enddate: "2022-05-31", fnum: 0.7, role: "MP", startdate: "2022-01-13", },{ dnum: "061806", enddate: "2022-05-31", fnum: 0.786, role: "MP", startdate: "2022-01-13", }] function selectProps(props){ return function(obj){ const newObj = {}; props.forEach(el =>{ newObj[el[1]] = obj[el[0]]; }); return newObj; } } let filteredObject = data.map(selectProps([['dnum','DNUM'],['fnum','fnum'],['role','Role Name']])) //if dont want to change key name send like this ['dnum','dnum'] console.log(filteredObject)

You have almost nailed it. Here is what you need to change to make it work:

// modify this line
let filteredObject = copyObjectProps(data, ['dnum', 'role', 'fnum'])

// to this
const filteredObject = data.map(item => {
  return copyObjectProps(item, ['dnum', 'role', 'fnum']))
}

Here is what happend:

  1. You are building the new Object right.
  2. You have missed that you need an Array of Objects. map is giving you the Array, your method is giving you the right Object. Good luck!

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