简体   繁体   中英

What kind of data structure would I use for this in JavaScript?

I have a class Person, with the fields firstname, lastname, age and zipcode. I need to store a large collection of these Person objects in memory. I need to be able to add and delete items, in addition to being able to sort and search by any of the fields. What data structure and mechanism would I use to accomplish this? Can anyone point me in the right direction?

I have a class Person, with the fields firstname, lastname, age and zipcode. I need to store a large collection of these Person objects in memory.

Then an array of object literals

[
    {
        firstName: John,
        lastName: Doe,
        age: 23,
        zipcode: 0987
    },{
        firstName: Jane,
        lastName: Doe,
        age: 21,
        zipcode: 0987
    }
]

I need to be able to add and delete items, in addition to being able to sort and search by any of the fields.

Array push , splice , sort and filter , respectively. There are actually more operations than just these basic four.

What data structure and mechanism would I use to accomplish this?

Arrays of objects . They're pretty much all you have for JS. All the rest are improvised structures that use these guys.

Use an array of objects.

[
    {
        firstName: Bill,
        lastName: Gates
        age: 20
        zipcode: 12345
    }, {
        firstName: Jimm,
        lastName: Winter
        age: 30
        zipcode: 65432
    }
]

Also you can use Underscore.js or Lo-Dash to work with such collections in elegant way.

Basically this is JSON that is universal format of data storing, filtering and transferring.

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