简体   繁体   English

Javascript根据另一个数组通过键对对象排序?

[英]Javascript sort an object by keys based on another Array?

How do you sort an object by keys based on another array in Javascript? 如何基于Javascript中的另一个数组通过键对对象排序?

This is the same question as here PHP Sort an Array by keys based on another Array? 这与这里的问题相同。PHP根据另一个数组通过键对数组进行排序?

But I need the same process for Javascript. 但是我需要使用与Javascript相同的过程。

Thanks 谢谢

The JavaScript specification does not require that object keys maintain their order, so it is not safe to attempt to sort them. JavaScript规范不要求对象键保持其顺序,因此尝试对它们进行排序并不安全。 It is up to each environment to implement the standard, and each browser does this differently. 实施标准取决于每种环境,每种浏览器的执行方式也不同。 I believe most modern browsers will sort keys on a first-in-first-out basis, but since it is not part of the standard, it is not safe to trust this in production code. 我相信大多数现代浏览器都会按照先进先出的顺序对键进行排序,但是由于它不是标准的一部分,因此在生产代码中信任它并不安全。 It may also break in older browsers. 在较旧的浏览器中也可能会中断。 Your best bet is to place your object keys into an array, sort that array and then access the values of the object by the sorted keys. 最好的选择是将对象键放入一个数组中,对该数组进行排序,然后通过排序后的键访问该对象的值。

var myObject = { d: 3, b: 1, a: 0, c: 2 },
    sortedKeys = Object.getOwnPropertyNames(myObject).sort();

You could then map the ordered values into a new array if you need that. 然后,可以根据需要将有序值映射到新数组中。

var orderedValues = sortedKeys.map(function (key) { return myObject[key]; });

As QED2000 pointed out, even if you create a new object, there's no guaranty that the properties will remain in a specific order. 正如QED2000指出的那样,即使您创建一个新对象,也无法保证这些属性将保持特定顺序。 However you can sort the keys depending on a different array. 但是,您可以根据不同的数组对键进行排序。

<script>
    function sortArrayByArray(a, b)
    {
        return order.indexOf(a) - order.indexOf(b);
    }
    var order = new Array('name', 'dob', 'address');
    var customer = new Array();
    customer['address'] = '123 fake st';
    customer['name'] = 'Tim';
    customer['dob'] = '12/08/1986';
    customer['dontSortMe'] = 'this value doesnt need to be sorted';
    var orderedKeys = Object.keys(customer).sort(sortArrayByArray);
    orderedKeys.forEach(function (key) {
        document.write(key + "=" + customer[key] + "<br/>");
    });
</script> 

The output is 输出是

dontSortMe=this value doesnt need to be sorted
name=Tim
dob=12/08/1986
address=123 fake st

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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