alim1990
alim1990

Reputation: 4972

JavaScript how to extract array properties into another array?

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"]

Upvotes: 2

Views: 2052

Answers (4)

Nicholas K
Nicholas K

Reputation: 15423

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

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

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!

Upvotes: 2

Martin Ackermann
Martin Ackermann

Reputation: 924

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

Upvotes: 1

Lior Pollak
Lior Pollak

Reputation: 3450

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" ]

Upvotes: 1

Related Questions