How can i extract all the element from object dynamically

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

Answers:

Answer

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])
  )
);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.