我有以下 JSON 数据:
var json = [{ "name":"A", "value":"valueA"},
{ "name":" ", "value":"VALUES"},
{ "name":"Z", "value":"values"},
{ "name":" ", "value":"VALUES12"},
{ "name":" ", "value":"VALUES123"},
{ "name":"B", "value":"valueBS"},
{ "name":" ", "value":"VALUES123"}];
我想按字母顺序对数据进行排序,但将空 名称
值保留在非空 名称之后的相同位置
。所以预期的输出是:
[{ "name":"A", "value":"valueA"},
{ "name":" ", "value":"VALUES"},
{ "name":"B", "value":"valueBS"},
{ "name":" ", "value":"VALUES123"},
{ "name":"Z", "value":"values"},
{ "name":" ", "value":"VALUES12"},
{ "name":" ", "value":"VALUES123"}]
我尝试过以下方法
function sortResults(prop, asc, array) {
arr = array.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]);
else return (b[prop] > a[prop]);
});
return arr;
}
并通过以下方式调用它
var sorted = sortResults('name', true, json);
这确实对数组进行了排序,但空白也被重新排序,这是我不想要的。解决这个问题的最佳方法是什么?
注意:我无法更改服务器上的 JSON 数据顺序,因为我无权访问它。
最佳答案
您可以尝试使用高阶函数来做到这一点。而且,您可以reduce您的数据以便对您的字段进行排序,然后 map结果。
通过使用高阶函数,您的代码将更具可重用性。因此,我们将执行映射和减少转换。
var json = [
{ "name":"A", "value":"valueA"},
{ "name":" ", "value":"VALUES"},
{ "name":"Z", "value":"values"},
{ "name":" ", "value":"VALUES12"},
{ "name":" ", "value":"VALUES123"},
{ "name":"B", "value":"valueBS"},
{ "name":" ", "value":"VALUES123"}
];
//Create a generator function in order to sort by specifing key
function sortBy(key){
return function(a, b) {
return a[key] < b[key]?-1:(a[key] > b[key])?1:0;
}
}
function sorting(json){
//Reduce my json data and start with empty array
var sorted = json.reduce(function(result, current){
return current.name !== ' '
//Build a sorted array
? result.concat(current).sort(sortBy('name'))
//Return current sorted array
: result
}, []);
return json.map(function(elm, index, self){
return elm.name !== ' '
//Retrieve the first element of sorted array by shifting it
? sorted.shift()
//Then, retrieve current elm in json array
: elm
});
}
console.log(sorting(json));
关于javascript - 忽略空白值对 json 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31960023/