How can i extract all the element from object dynamically

前端 未结 1 1798
萌比男神i
萌比男神i 2021-01-16 22:51

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 w

1条回答
  •  没有蜡笔的小新
    2021-01-16 23:54

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

    0 讨论(0)
提交回复
热议问题