How can i extract all the element from object dyna

2020-03-31 08:41发布

问题:

How can I extract the specific column from an object, I have a column array and I want these fields extracted from an object which will be constructed by map loop function which is the item. Now here, how can check my fields dynamically. i don't want item[col[0]] like this. please tell me a short cut.

const person = [{
  firstName: "Nick",
  lastName: "Anderson",
  age: 35,
  sex: "M"
},
{
  firstName: "yopm",
  lastName: "Geyun",
  age: 36,
  sex: "M"
}]

const col=['firstName' , 'age']

return person.map(item=>{
     var i=0;        
     return [
         //How can i confgure here , that i show stop increment or not.
        item[col[i]],
        item[col[i+1]]
//here i want to fetch my colums['firstName' , 'age] from item {
//{firstName: "Nick",lastName: "Anderson",age: 35,sex: "M"} dynamically.
]   
})
}

console.log(func())

How can I configure here, that I show stop increment or not. item[col[i]], item[col[i+1]] i want it dynamically

回答1:

Just iterate over the col properties and .map to a new array. You could also consider changing the person variable name to people (or something like that), because it's a collection of persons, not a singular person, reducing the chance of confusion:

const people = [{
    firstName: "Nick",
    lastName: "Anderson",
    age: 35,
    sex: "M"
  },
  {
    firstName: "yopm",
    lastName: "Geyun",
    age: 36,
    sex: "M"
  }
]

const col = ['firstName', 'age']

console.log(
  people.map(
    person => col.map(prop => person[prop])
  )
);