简体   繁体   中英

Javascript array inherit keys of object

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?

Make items into objects and push to the array:

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

arr.push(item);

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)

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 console.table :

 var items = []; items.push({ prop1: 1, prop2: 2, prop3: 3 }); items.push({ prop1: 10, prop2: 20, prop3: 30 }); console.table(items); // Run, then do F12, then look in "Console" tab

To see the results you need to Run the snippet, then press F12 to open the Developer Tools , then look in the "Console" tab to see the output. Here is a screenshot of it:

控制台输出的屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM