将提供的JSON重新排序为指定格式

时间:2017-07-26 11:10:01

标签: javascript arrays json

我需要一种优化的方法来重新排序JavaScript中的以下JSON:

 [
 {"Values":["2005","Australia","$304749.10"]},
 {"Values":["2005","France","$143130.80"]},
 {"Values":["2006","Australia","$651979.82"]},
 {"Values":["2006","France","$332496.01"]},
 ]

采用以下格式:

 [
 {"Values":["Australia","2005","$304749.10"]},
 {"Values":["Australia","2006","$651979.82"]},
 {"Values":["France","2005","$143130.80"]},
 {"Values":["France","2006","$332496.01"]},

 ]

3 个答案:

答案 0 :(得分:2)

var data=[
  {"Values":["2005","Australia","$304749.10"]},
  {"Values":["2005","France","$143130.80"]},
  {"Values":["2006","Australia","$651979.82"]},
  {"Values":["2006","France","$332496.01"]},
]

首先可以重新排序道具:

data=data.map(({Values:[year,location,price]})=>({Values:[location,year,price}]));

然后在第一个道具后按字母顺序排序:

data.sort(({Values:[loca]},{Values:[locb]})=>loca.localeCompare(locb));

http://jsbin.com/yekiropozu/edit?console

请注意,这使用ES6对象解构...

答案 1 :(得分:1)

您可以先交换内部数组的前两项,然后按国家/地区按年份对整个数组进行排序。



var array = [{ Values: ["2005", "Australia", "$304749.10"] }, { Values: ["2005", "France", "$143130.80"] }, { Values: ["2006", "Australia", "$651979.82"] }, { Values: ["2006", "France", "$332496.01"] }];

array.forEach(a => [a.Values[0], a.Values[1]] = [a.Values[1], a.Values[0]]);
array.sort((a, b) => a.Values[0].localeCompare(b.Values[0]) || a.Values[1] - b.Values[1]);

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)

<script>
var data = [
 {"Values":["2005","Australia","$304749.10"]},
 {"Values":["2005","France","$143130.80"]},
 {"Values":["2006","Australia","$651979.82"]},
 {"Values":["2006","France","$332496.01"]},
 ];

 var data2 = data;

 for(i=0;i<data.length;i++){
 data2[i].Values[1] = data[i].Values[0];
 data2[i].Values[0] = data[i].Values[1];
}
console.log(data2);
</script>