Before diving into coding, it's important to establish the desired data format. Your provided example has a syntax error:
tags: ["11111111":["12345678"], "22222222", "33333333", "44444444"]
This should be corrected to:
{ tags: [ { "11111111": ["12345678"] }, "22222222", "33333333", "44444444"] }
While we fixed the syntax error, there are other improvements to consider. Although Javascript may not flag it, tags
is now an array of mixed types - containing both objects ({ "11..": ["123..."] }
) and strings ("222..", "333.."
). It would be better formatted like this:
{
tags: {
"11111111": [ "12345678" ],
"22222222": [ ],
"33333333": [ ]
}
}
We've transformed tags
into an object that holds an array of IDs for each tag, with empty arrays where no IDs exist.
To initialize this object, iterate over the tag array:
const tags = ["11111111", "22222222", "33333333", "44444444"];
const tagGroups = {};
tags.forEach(t => { tagGroups[t] = []; });
console.log(tagGroups);
With the empty groups set up, you can proceed to process the data.
const tags = ["11111111", "22222222", "33333333", "44444444"];
const data = [{
"id": "12345678",
"tagging": {
"tags": [{
"id": "11111111"
}]
}
}];
const tagGroups = {};
tags.forEach(t => {
tagGroups[t] = [];
});
data.forEach(d => {
d.tagging.tags.forEach(tag => {
tagGroups[tag.id].push(d.id);
});
});
console.log(tagGroups);
You can determine how many times a tag appears by calling tagGroups[id].length
. For example:
console.log(tagGroups["11111111"].length); // Outputs `1`
There are alternative ways to write this code more succinctly, but I aimed for readability here.
Note: if a tag in your data
isn't included in the tags
array, the code will encounter errors.