当我使用Lodash()的orderBy函数时,它返回具有正确顺序的数组,但是通过简单的键0,1,2,3更改索引... 我到处搜索了一下,但我找不到解决方法来保留我的钥匙。
示例:
#If you are not logged into the US-South https://api.ng.bluemix.net
region, change the image registry location to match your region.
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: ibmliberty-deployment
spec:
replicas: 3
template:
metadata:
labels:
app: ibmliberty
spec:
containers:
- name: ibmliberty
image: registry.ng.bluemix.net/ibmliberty
---
apiVersion: v1
kind: Service
metadata:
name: ibmliberty-loadbalancer
spec:
type: LoadBalancer
selector:
app: ibmliberty
ports:
- protocol: TCP
port: 9080
Data :
var a = {
"65191320": {
"date":"20180220",
"comment":"Hello world"
},
"849165164": {
"date":"20180221",
"comment":"Hello world"
}
}
main.js :
var b = _.orderBy(a, ['date'], ['desc']);
console.log(b);
Output :
如您所见,密钥已更改。那是常见的吗?如何将键保持在食指上? 先感谢您。
答案 0 :(得分:0)
TL; DR:无法重新排序普通对象属性。
JavaScript对象无法保证属性顺序。只有数组或Map才能保证。因此,首先订购普通对象毫无意义。
此处another answer that expands on this subject。
$.getScript('/get_script', function() {
// put logic to run after the script has loaded here...
// note that you don't need your .html(data.myScript) any more
MyScript.initScript();
console.log(MyScript.random_string);
});
// in your external script:
var MyScript = {
initScript = function() {
this.random_string = Math.random().toString(36).substring(7);
},
random_string: null;
}
函数仅适用于数组和数组。在下面,它使用orderBy()
,如下所示:
baseSortBy()
注意function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
循环体:它设置while
。如果array[length]
是一个对象,它会将属性设置为数字。
答案 1 :(得分:0)
您可以通过执行此操作来解决它。
_.fromPairs(_.orderBy(_.toPairs(a), ['date'], ['desc']))
结果应该像您期望的那样。
干杯。