Home > other >  Javascript array inherit keys of object
Javascript array inherit keys of object

Time:03-15

I'm used to program on PowerShell and fairly new to JavaScript. In PowerShell you can create an array of custom objects like that : You have an object with 3 properties of value 1,2,3 for $item1 :

Property1 Property2 Property3
--------- --------- ---------
        1         2         3

Same properties with values 10,20,30 for $item2

Property1 Property2 Property3
--------- --------- ---------
       10        20        30

And if you add them to an arraylist it automatically inherits their properties :

$collectionVariable = New-Object System.Collections.ArrayList
$collectionVariable.Add($item) | Out-Null
$collectionVariable.Add($item2) | Out-Null
$collectionVariable

Property1 Property2 Property3
--------- --------- ---------
        1         2         3
       10        20        30

I have tried to do the same in JavaScript but ultimately failed as each added object appears as a new key.

var arraylist = new Array();
arraylist.push(item);

It seems that it does not work that way as the arraylist does not inherit item's keys.

How can I do so that my arraylist inherit the keys of my objects ?

CodePudding user response:

Make items into objects and push to the array:

const item = {
   prop1: 1,
   prop2: 2,
   prop3: 3
}

arr.push(item);

CodePudding user response:

If you want your keys of object to be elements of the array list : Do this ,

const item = {
   prop1: 1,
   prop2: 2,
   prop3: 3
}

let arr = Object.keys(item);
console.log(arr)

If you want , values of object to be elements of array list , do this :

const item = {
   prop1: 1,
   prop2: 2,
   prop3: 3
}

let arr = Object.values(item)
console.log(arr)

CodePudding user response:

ArrayList is a rather dumb (and IMO very much outdated) collection type. It only supports the .NET type Object, and it certainly does not inherit anything.

PowerShell on the other hand has smart logic to see beyond the stored objects and to print them using their properties, and to group on those properties if they are the same. What you see printed is because PowerShell is smart, not because ArrayList is smart (on the contrary).

Javascript has a similarly smart printing function, and that is Screenshot of Console output

  • Related