Skip to content Skip to sidebar Skip to footer

Can I Prevent Automatic Sort Of Js Object Numeric Property?

Given the following JS Object I want this to return in the order it is in. e.g. console.log(stk[24]); should return: 221,220,224,226,198 instead of 198,220,221,224,226 I want to

Solution 1:

can I prevent automatic sort of JS Object numeric property?

You can't. But you shouldn't be paying attention to or caring about the order of properties in JavaScript objects anyway. While they have an order (now), it's best to act as though they're unordered. If you want a specific order, use an array (which is also an object, and that's part of why property names that are integer indexes are visited in numeric order).

The problem here is that the I have no control over the construction of var stk; because it is built inside a PHP code from a third party plugin.

If that's the case, you can't do anything about it. If you could get the PHP to output it as a string, e.g.:

var stk = "{3:{221:1,220:1,224:1,226:1,198:1},24:{221:1,220:1,224:1,226:1,198:1},33:{198:1},9:{223:1,221:1,220:1,224:1,226:1,198:1},156:{220:1,224:1,226:1}}";

...then you could parse it yourself and maintain order. But if you can't even do that, there's nothing you can do about it.

You might be able to bend over backward and find it in the text of the JavaScript, if it's an inline script tag rather than a .js file (if it's a .js file, your ability to read it will depend on whether it's from the same origin as your page).

For example:

var text = $("#from-plugin").text();
var match = /var stk=(\{.*\};)/.exec(text);
console.log(match ? match[1] : "Couldn't find it");
<scriptid="from-plugin">// other stuffvar stk={3:{221:1,220:1,224:1,226:1,198:1},24:{221:1,220:1,224:1,226:1,198:1},33:{198:1},9:{223:1,221:1,220:1,224:1,226:1,198:1},156:{220:1,224:1,226:1}};
// other stuff</script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

...and then, you'd have to parse it into an array of arrays. Probably not particularly difficult, in this case.

Post a Comment for "Can I Prevent Automatic Sort Of Js Object Numeric Property?"