我有这样的数据:
def fun(num = int(input())):
print("num:",num)
fun()
将数据打印到准备好的模板中。抛开它,我想要的是"已购买"和"租"每个项目的部分按字母顺序排序。第1项和第2项适用于此,但第3项和第4项则不适用。问题是从服务器项目可以带有不同种类的数据。对于例如第2项仅与已购买,因此添加了0,0的租金组件。
我在这里看到了一些字符串排序函数,但它们是针对单个数组的,我在这里没有采用它们。
答案 0 :(得分:-1)
//所以你的意思是你基本上想要'已购买'来之前出租'?正如其他人所说,物体确实没有秩序。因此,如果您想要控制顺序,您可以使用lodash或类似的东西将其映射到数组。
_ = require('lodash');
_.map(properties, (property, index) => {
let thisProp = {};
thisProp[`Item ${index + 1}`] = [{Purchased: property.Purchased}, {Rent: property.Rent}];
return thisProp;
});
这将以以下形式返回数据:
[
{
"Item 1": [
{
"Purchased": {
"quantity": "5.000",
"cost": "80.000"
}
},
{
"Rent": {
"quantity": "45.000",
"cost": "25200.000"
}
}
]
},
{
"Item 2": [
{
"Purchased": {
"quantity": "35.000",
"cost": "25000.000"
}
},
{
"Rent": {
"quantity": "0.0",
"cost": "0.0"
}
}
]
}
] //etc.
答案 1 :(得分:-1)
你可以做@Jonny Rathbone所建议的,而不必使用任何进一步的库。只是做
for (var p in DAT)
DAT[p]={Purchased:DAT[p].Purchased,
Rent:DAT[p].Rent};
JSON.stringify()现在按所需顺序列出属性。但是,正如@xufox和@blex已经评论过:JavaScript中的属性顺序并没有真正定义,因此在这里实现的结果可能无法在所有浏览器或未来版本的JavaScript中持续使用。
答案 2 :(得分:-1)
以下代码段在最流行的浏览器中执行您所请求的内容。但是,正如您在下面提到的问题,对象保持其顺序的规范并没有强制执行。
const data = {
"Item 1": {
"Purchased": {
"quantity": "5.000",
"cost": "80.000"
},
"Rent": {
"quantity": "45.000",
"cost": "25200.000"
}
},
"Item 2": {
"Purchased": {
"quantity": "35.000",
"cost": "25000.000"
},
"Rent": {
"quantity": "0.0",
"cost": "0.0"
}
},
"Item 3": {
"Rent": {
"quantity": "25.000",
"cost": "50.000"
},
"Purchased": {
"quantity": "0.0",
"cost": "0.0"
}
},
"Item 4": {
"Rent": {
"quantity": "5.000",
"cost": "80.000"
},
"Purchased": {
"quantity": "0.0",
"cost": "0.0"
}
}
}
function sortItem(item) {
const sortedKeys = Object.keys(item).sort()
return sortedKeys.reduce((accu, key) => ({ ...accu, [key]: item[key] }), {})
}
const result = Object.keys(data).reduce((accu, key) => ({ ...accu, [key]: sortItem(data[key]) }), {})
console.log(result)

因此,我推荐以下使用数组的解决方案(总是保证结果的顺序):
const data = {
"Item 1": {
"Purchased": {
"quantity": "5.000",
"cost": "80.000"
},
"Rent": {
"quantity": "45.000",
"cost": "25200.000"
}
},
"Item 2": {
"Purchased": {
"quantity": "35.000",
"cost": "25000.000"
},
"Rent": {
"quantity": "0.0",
"cost": "0.0"
}
},
"Item 3": {
"Rent": {
"quantity": "25.000",
"cost": "50.000"
},
"Purchased": {
"quantity": "0.0",
"cost": "0.0"
}
},
"Item 4": {
"Rent": {
"quantity": "5.000",
"cost": "80.000"
},
"Purchased": {
"quantity": "0.0",
"cost": "0.0"
}
}
}
function sortItem(item) {
const sortedKeys = Object.keys(item).sort()
return sortedKeys.reduce((accu, key) => [...accu, { key, ...item[key] }], [])
}
const sortedKeys = Object.keys(data).sort()
const result = sortedKeys.reduce((accu, key) => [...accu, { key, info: sortItem(data[key]) }], [])
console.log(result)