我如何动态地从对象中提取所有元素 [英] How can i extract all the element from object dynamically
问题描述
我如何从对象中提取特定的列,我有一个列数组,我希望从对象中提取这些字段,该对象将由作为对象的map loop函数构造. 现在在这里,如何动态检查我的字段.我不要这样的item [col [0]]. 请告诉我捷径.
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())
如何在此处配置是否显示停止增量. 项目[col [i]], 项目[col [i + 1]] 我要动态
How can I configure here, that I show stop increment or not. item[col[i]], item[col[i+1]] i want it dynamically
推荐答案
只需将col
属性和.map
迭代到新数组.您还可以考虑将person
变量名更改为people
(或类似名称),因为它是个人的 collection 而不是单身的人,从而减少了混淆的可能性:
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])
)
);
这篇关于我如何动态地从对象中提取所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!