[英]JSON object with key numbers and values of recurring strings separated in to string array with count
我有一個下面提到的格式的 json 對象。 我需要一個函數來返回課程名稱和計數。 從這個問題可以回答我的問題。 這個答案是針對不同的 json 對象的。 [“高級數據結構”,3],[“高級-r”,3]
// Size of the JSON Object
let json = {
"0": "advanced-data-structures",
"1": "advanced-data-structures",
"145": "advanced-data-structures",
"149": "advanced-excel",
"185": "advanced-excel",
"186": "advanced-r",
"202": "advanced-r",
"203": "advanced-r",
"204": "advanced-trading-algorithms",
"205": "advanced-trading-algorithms",
"206": "agile-planning-for-software-products",
"276": "agile-planning-for-software-products",
"277": "agile-planning-for-software-products",
"278": "algorithmic-thinking-1",
"282": "algorithmic-thinking-1",
"283": "algorithmic-thinking-1"
};
let arrayOfCourses = [];
let count = Object.keys(json).length;
Object.keys(json).forEach(function(prop) {
console.log('Key Count', prop)
});
Object.values(json).forEach(function (prop){
console.log('Value', prop);
// I would need something like this
// ["advanced-data-structures", 3],
// ["advanced-r", 3]
});
for(var i = 0 ; i< count; i++) {
console.log(json[i])
arrayOfCourses.push(json[i]);
}
let uniqueItems = Array.from(new Set(arrayOfCourses))
// unique Items removing duplicates.
console.log(uniqueItems)
您可以先獲取對象的 Object.values,然后根據課程名稱將其減少:
const json = { "0": "advanced-data-structures", "1": "advanced-data-structures", "145": "advanced-data-structures", "149": "advanced-excel", "185": "advanced-excel", "186": "advanced-r", "202": "advanced-r", "203": "advanced-r", "204": "advanced-trading-algorithms", "205": "advanced-trading-algorithms", "206": "agile-planning-for-software-products", "276": "agile-planning-for-software-products", "277": "agile-planning-for-software-products", "278": "algorithmic-thinking-1", "282": "algorithmic-thinking-1", "283": "algorithmic-thinking-1" }; const result = Object.entries(Object.values(json).reduce((a,e)=>{ a[e] = a[e] || 0; a[e]+=1; return a; },{})); console.log(result);
在 reduce 之后,您可以獲取該結果對象的entries
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.