javascript - JS - Deleting unnecessary objects inside a list of objects -
i have object inside node server contains thousands of objects, each object person , has totalscore. looks this:
var mainobject = { //it's unsorted, no need sort anyway john: {totalscore: 5, info: "no"}, james: {totalscore: 3, info: "no"}, lee: {totalscore: 55, info: "no"} } now, want remain 1000 objects inside mainobject, problem need wipe lowest scores delete mainobject[name] before sending client(other solution other delete acceptable).
the indexes of each object inside mainobject shouldn't switched 1 another(there reason), lowest scores need go , list should sent client object , @ 1000 length.
you're attempting apply array-based concepts length , ordering object. won't do.
to achieve want, you're going have convert object array. 1 way so:
var mainobject = { john: {totalscore: 5, info: "no"}, james: {totalscore: 3, info: "no"}, lee: {totalscore: 55, info: "no"}, }; var mainarray = object.keys(mainobject).map(function (name) { return object.assign({}, mainobject[name], {name}); }); console.log(mainarray); you can sort array score , return n highest entries:
var mainarray = [ { "totalscore": 5, "info": "no", "name": "john" }, { "totalscore": 3, "info": "no", "name": "james" }, { "totalscore": 55, "info": "no", "name": "lee" } ] mainarray.sort(function (a, b) { return b.totalscore - a.totalscore; }); console.log(mainarray.slice(0, 1000)); if reason client absolutely needs object rather array of objects, can convert back:
var mainarray = [ { "totalscore": 5, "info": "no", "name": "john" }, { "totalscore": 3, "info": "no", "name": "james" }, { "totalscore": 55, "info": "no", "name": "lee" } ]; var mainobject = mainarray.reduce(function (prev, curr) { var name = curr.name; delete curr.name; prev[name] = curr; return prev; }, {}); console.log(mainobject); but @ point you've done absurd amount of work achieve goal. enough work implies an xy problem, , should reconsider decisions have led point.
Comments
Post a Comment