javascript - Implementing an array intersection with JSON values -
i have array containing json objects such
validtags = [{"tag":"tag1"}, {"tag":"tag2"}];
and
items = [{"id":123456, "tag":"tag1"}, {"id":123456, "tag":"tag2"}, {"id":7890, "tag":"tag1"}];
and i'm trying figure out id's have both 'tags' first array.
e.g. output be:
[{"id":123456, "tag":"tag1 tag2"}]
with both matching tags combined 1 string.
any ideas how should going doing this? chatting users in javascript chatroom , suggested array intersection used, i'm not exclusively sure how utilize intended outcome json :(
all answers/help appreciated!
many thanks
here solution using both objects , arrays:
validtags = [{"tag":"tag1"}, {"tag":"tag2"}]; items = [{"id":123456, "tag":"tag1"}, {"id":123456, "tag":"tag2"}, {"id":7890, "tag":"tag1"}]; accumulate = {}; // create utilize of hashing of javascript objects merge tags. items.foreach(function(e) { if(accumulate[e.id] == undefined) accumulate[e.id] = [e.tag]; else accumulate[e.id].push(e.tag); }); // convert object array. field 'tags' still array. var result0 = []; for(var id in accumulate) result0.push({"id": id, tags: accumulate[id]}); var result = result0.filter( // first cross out not contain every tag. function(e) { homecoming validtags.every( function(e1) { homecoming e.tags.indexof(e1.tag) != -1; }); }) // create 'tags' array string. .map(function(e) { homecoming {"id": e.id, "tags": e.tags.join(" ")}; });
javascript arrays json
No comments:
Post a Comment