2

I need to map an array coming from a server to change its fields into fields that are understandable by another server, so I can upload it into the second server.

My first challenge is to get the field names of the first array coming from the first server, display them to the user, to edit them and then using array.map() I will create a new array with the user defined field names.

My first step is to get the array main field names. Lets say I have the following:

array = [{'name': 'John', 'lastname' :'Doe'},{'name': 'Roe', 'lastname' :'Doe'}]

The result would be like:

arrayFields = [{name, lastname}]

I tried to use getOwnPropertyNames():

getProp(){
    console.log(Object.getOwnPropertyNames(this.array))
}

The result was like:

["0", "1", "length"]

0: "0"

1: "1"

2: "length"

I then tried with Object.assign() as mentioned in this stack question:

 getObject(){
    let newObject = (Object.assign(this.array))
    console.log(Object.getOwnPropertyNames(newObject))
 }

But it was the same as previous result.

Here is the stackblitz I am working with.

The wanted result is like: ["name", "lastname"]

alim1990
  • 4,656
  • 12
  • 67
  • 130

4 Answers4

2

You can use Set() and .flatMap() combination also. By using them you have more flexible way to extract all the properties from each elements of the original array. For example if you have different properties in some elements.

Try the following:

const array = [{'name': 'John', 'lastname' :'Doe'},{'name': 'Roe', 'lastname' :'Doe'}];

const result = new Set(array.flatMap(e => Object.keys(e), []));

console.log(Array.from(result));

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

If they're all in the same format, you can take the first element and extract its keys:

const a = [{'name': 'John', 'lastname' :'Doe'},{'name': 'Roe', 'lastname' :'Doe'}];
const dummyEntry = a[0];
console.log(Object.keys(dummyEntry));

For your objects it would give [ "name", "lastname" ]

Lior Pollak
  • 3,362
  • 5
  • 27
  • 48
  • What happens when we have different structure for each elements? I mean the solution is good until we have extra properties in the second element in the original array. – norbitrial Mar 24 '20 at 09:15
  • Hence "If they're all in the same format". If they're not, better off to use combination of set and map as you suggested. – Lior Pollak Mar 24 '20 at 09:28
1

Your getProp() function is almost correct, except you need to call getOwnPropertyNames on an element within the array:

getProp(){
    console.log(Object.getOwnPropertyNames(this.array[0]));
}
Martin Ackermann
  • 884
  • 6
  • 15
1

Another variant would be:

let keySet = new Set();
this.array.forEach(e => Object.keys(e).forEach(i => keySet.add(i)));
console.log("keySet : ", Array.from(keySet));
Nicholas K
  • 15,148
  • 7
  • 31
  • 57