0

I am new to JS. Programmatically I need to find propery names of multidimensional array. Expected Output - ["name", "position", "salary", etc.]

When I am using map I am getting values of "name" data.map(item => item.name).

var data = [
        {
            "name": "Tiger Nixon",
            "position": "System Architect",
            "salary": "320800",
            "start_date": "2011\/04\/25",
            "office": "Edinburgh",
            "rating": "5421"
        },
        {
            "name": "Garrett Winters",
            "position": "Accountant",
            "salary": "170750",
            "start_date": "2011\/07\/25",
            "office": "Tokyo",
            "rating": "8422"
        },
        {
            "name": "Ashton Cox",
            "position": "Junior Technical Author",
            "salary": "86000",
            "start_date": "2009\/01\/12",
            "office": "San Francisco",
            "rating": "1562"
        },
        {
            "name": "Cedric Kelly",
            "position": "Senior Javascript Developer",
            "salary": "433060",
            "start_date": "2012\/03\/29",
            "office": "Edinburgh",
            "rating": "6224"
        }]
Ujjawal Bhandari
  • 1,333
  • 1
  • 8
  • 16

1 Answers1

1

Using Object#keys:

const getPropertyNames = (arr = []) => arr.length > 0 ? Object.keys(arr[0]) : [];

const data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" } ];
console.log( getPropertyNames(data) );
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48