자식 키인 y
키를 사용하여 세 개의 기본 JSON 키 (neutral
, positive
,)를 정렬하는 방법을 찾고 있습니다.JSON 객체의 자식 키를 자식 키 값으로 정렬
{
"chartSeries" : {
"negative" : [ {
"y" : 1505,
"url" : "http://www.test.com/1"
}, {
"y" : 425,
"url" : "http://www.test.com/2"
}, {
"y" : 1046,
"url" : "http://www.test.com/3"
} ],
"neutral" : [ {
"y" : 10,
"url" : "http://www.test.com/4"
}, {
"y" : 1,
"url" : "http://www.test.com/5"
}, {
"y" : 2,
"url" : "http://www.test.com/6"
} ],
"positive" : [ {
"y" : 230,
"url" : "http://www.test.com/7"
}, {
"y" : 50,
"url" : "http://www.test.com/8"
}, {
"y" : 483,
"url" : "http://www.test.com/9"
} ]
}
}
의 내가 y
의 값으로 내림차순 negative
값을 정렬 할 가정 해 봅시다, 다음 내 JSON은 다음과 같아야합니다 :
{
"chartSeries" : {
"negative" : [ {
"y" : 1505,
"url" : "http://www.test.com/1"
}, {
"y" : 1046,
"url" : "http://www.test.com/3"
}, {
"y" : 425,
"url" : "http://www.test.com/2"
} ],
"neutral" : [ {
"y" : 10,
"url" : "http://www.test.com/4"
}, {
"y" : 2,
"url" : "http://www.test.com/6"
}, {
"y" : 1,
"url" : "http://www.test.com/5"
} ],
"positive" : [ {
"y" : 230,
"url" : "http://www.test.com/7"
}, {
"y" : 483,
"url" : "http://www.test.com/9"
}, {
"y" : 50,
"url" : "http://www.test.com/8"
} ]
}
}
이
는 JSON 객체를 설정하는 방법입니다음수 요소가 내림차순 y 값에 따라 정렬되고 중성선 및 음수 값이 정확히 동일한 순서로 정렬되는 방식에 유의하십시오.
나는 JSON.parse()
를 사용하여 자바 스크립트 객체로 파싱 한 후 정렬 기능을 사용하여 시도 :
function sortResults(data, prop, asc) {
sorted_data = data.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]);
else return (b[prop] > a[prop]);
});
return sorted_data;
}
을하지만 난 그냥 얻을 : 내 디버거에서 "형식 오류 data.sort는 함수가 아닙니다."
설명이나 조언을 주시면 감사하겠습니다.
'sort()'는 [배열 프로토 타입] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)의 메소드입니다. – Teemu
@ Teemu의 의견에 이어 [MDN 참고] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse), JSON.parse()'는 Object를 반환합니다. – Nit