JavaScript/jQuery统计JSON:拆分keyword字段并统计的技术问询
Split JSON Keyword Field into Array & Count Discrete Entries
Got it, let's tackle this problem! So you want to take the keyword field from each entry in your JSON, split it into an array of individual keywords, then count how many times each discrete keyword shows up across all items—right?
Here's how to modify your existing code to make this work:
Step-by-Step Explanation
- Initialize a count object: We'll use this to track how many times each unique keyword appears.
- Split & clean each keyword string: For every JSON item, we split the
keywordvalue into an array (adjust the separator based on your actual data), trim whitespace from each entry, and filter out any empty strings (to avoid counting accidental blanks). - Count each discrete keyword: Loop through the cleaned array, incrementing the count for each keyword in our tracking object.
- Display the results: Finally, we output the formatted count object to your HTML element.
Modified Code
var globalJsonVar; $.getJSON("index.json", function(json) { globalJsonVar = json; // Object to hold counts for each discrete keyword var keywordCounts = {}; json.forEach(function(item) { // Skip if the keyword field is missing or empty if (!item.keyword) return; // Split the keyword string into an array (adjust separator as needed) // Example uses comma as separator; change to ';' / '\s+' (for spaces) if needed var splitKeywords = item.keyword.split(',') .map(keyword => keyword.trim()) // Remove extra whitespace around each keyword .filter(keyword => keyword !== ''); // Filter out empty strings // Count each individual keyword splitKeywords.forEach(function(keyword) { // Initialize count to 0 if keyword isn't in the object yet if (!keywordCounts[keyword]) { keywordCounts[keyword] = 0; } keywordCounts[keyword]++; }); }); // Display formatted results (the null, 2 adds indentation for readability) $('#menu').text(JSON.stringify(keywordCounts, null, 2)); });
Key Notes
- Adjust the separator: If your keywords are separated by something other than commas (like semicolons or spaces), just change the argument in
split(','). For example:- Use
split(';')for semicolon-separated keywords - Use
split(/\s+/)for keywords separated by one or more spaces
- Use
- Cleaning data: The
map(trim)andfiltersteps ensure we don't count keywords with extra whitespace (like" apple"vs"apple") or empty strings from malformed entries. - Readable output: Using
JSON.stringify(keywordCounts, null, 2)formats the result with indentation, making it easier to read in the browser.
内容的提问来源于stack exchange,提问作者east1999
相关产品推荐
相关产品推荐

