1

So I have this JSON Object. Let's call it var dataFetched

var dataFetched = {
    "status": "ok",
    "count": 4,
    "count_total": 4,
    "pages": 1,
    "posts": [
    {
      "id": 57,
      "type": "keyword",
      "slug": "crime-scene-investigation-csi",
      "url": "http://keyjargon.com/keyword/crime-scene-investigation-csi/",
      "status": "publish",
      "title": "Crime Scene Investigation (CSI)",
      "title_plain": "Crime Scene Investigation (CSI)",
      "content": "",
      "excerpt": "",
      "date": "2015-11-07 05:01:51",
      "modified": "2015-11-07 05:01:51",
      "categories": [
        {
          "id": 8,
          "slug": "law",
          "title": "Law",
          "description": "",
          "parent": 0,
          "post_count": 1
        }
      ],
      "tags": [

      ],
      "author": {
        "id": 1,
        "slug": "admin",
        "name": "admin",
        "first_name": "",
        "last_name": "",
        "nickname": "admin",
        "url": "",
        "description": ""
      },
      "comments": [

      ],
      "attachments": [

      ],
      "comment_count": 0,
      "comment_status": "closed",
      "custom_fields": {

      }
    },
    {
      "id": 50,
      "type": "keyword",
      "slug": "fx",
      "url": "http://keyjargon.com/keyword/fx/",
      "status": "publish",
      "title": "FX",
      "title_plain": "FX",
      "content": "",
      "excerpt": "",
      "date": "2015-11-05 10:07:17",
      "modified": "2015-11-05 10:22:10",
      "categories": [
        {
          "id": 3,
          "slug": "business",
          "title": "Business",
          "description": "",
          "parent": 0,
          "post_count": 2
        }
      ],
      "tags": [

      ],
      "author": {
        "id": 1,
        "slug": "admin",
        "name": "admin",
        "first_name": "",
        "last_name": "",
        "nickname": "admin",
        "url": "",
        "description": ""
      },
      "comments": [

      ],
      "attachments": [

      ],
      "comment_count": 0,
      "comment_status": "closed",
      "custom_fields": {

      }
    },
    {
      "id": 48,
      "type": "keyword",
      "slug": "common-core",
      "url": "http://keyjargon.com/keyword/common-core/",
      "status": "publish",
      "title": "Common CORE",
      "title_plain": "Common CORE",
      "content": "",
      "excerpt": "",
      "date": "2015-11-05 10:06:40",
      "modified": "2015-11-07 04:58:06",
      "categories": [
        {
          "id": 2,
          "slug": "technology",
          "title": "Technology",
          "description": "",
          "parent": 0,
          "post_count": 3
        }
      ],
      "tags": [

      ],
      "author": {
        "id": 1,
        "slug": "admin",
        "name": "admin",
        "first_name": "",
        "last_name": "",
        "nickname": "admin",
        "url": "",
        "description": ""
      },
      "comments": [

      ],
      "attachments": [

      ],
      "comment_count": 0,
      "comment_status": "closed",
      "custom_fields": {

      }
    },
    {
      "id": 46,
      "type": "keyword",
      "slug": "api",
      "url": "http://keyjargon.com/keyword/api/",
      "status": "publish",
      "title": "API",
      "title_plain": "API",
      "content": "",
      "excerpt": "",
      "date": "2015-11-05 10:06:19",
      "modified": "2015-11-05 10:21:47",
      "categories": [
        {
          "id": 2,
          "slug": "technology",
          "title": "Technology",
          "description": "",
          "parent": 0,
          "post_count": 3
        }
      ],
      "tags": [

      ],
      "author": {
        "id": 1,
        "slug": "admin",
        "name": "admin",
        "first_name": "",
        "last_name": "",
        "nickname": "admin",
        "url": "",
        "description": ""
      },
      "comments": [

      ],
      "attachments": [

      ],
      "comment_count": 0,
      "comment_status": "closed",
      "custom_fields": {

      }
      }
      ]
}

I want to rearrange this result to link the Category title :

dataFetched.posts[i].categories[0].title 

to the Post title :

dataFetched.post[i].title

so that each category displays all the posts titles related to it. I want my object (whether multi-demmensional array or another object) to be able to retrieve all the Posts titles related to the category.

Maybe something like this :

   [Category1: {Post_titleA, PostTitleB, PostTitleC}, Category2: {PostTileF, PostTileX}, etc ] where each category can retrieve all its posts.( The format does not matter as long the Object with Category title X can retrieve all posts titles that belong to it ).

How do I do this in Javascript ? The result variable is not static but its format is the same as the one posted here.

This is what I tried so far.

  // Function to sort unique values of an array
  function sort_unique(arr) {
      arr = arr.sort(function (a, b) { return a*1 - b*1; });
      var ret = [arr[0]];
      for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
        if (arr[i-1] !== arr[i]) {
            ret.push(arr[i]);
        }
     }
     return ret;
 }

 //Define two arrays to be used for categories and Keywords
 var keywords = [];
 var industries = [];

  //Fill up the categories(Industries) array and the keywords one
  for ( var i = 0, iLen = dataFetched.count; i < iLen; i++) {

    keywords[i] = dataFetched.posts[i].title;
    industries[i] = dataFetched.posts[i].categories[0].title;
  }

  // Sort and eliminate duplication of category and keyword names
  keywords = sort_unique(keywords);
  industries =  sort_unique(industries);

  // Now time for trouble: Define a multi-dimmensional array that links each category/industry to its keywords **This is where I AM STUCK**
  ind = new Array;
  for(i=0; i<industries.length;i++){
    ind[i] = new Array;
  }     
  for(i=0;i<dataFetched.count;i++){
    ind[i][0]= dataFetched.posts[i].categories[0].title;        
    for(j=0;j<dataFetched.count;j++){
        var count  = ind[i].length;
        if(ind[i][0] == dataFetched.posts[j].categories[0].title){
            ind[i][count] = dataFetched.posts[j].title;
        }

    }
}
3
  • what code have you written to solve the problem? Commented Nov 8, 2015 at 19:49
  • Please include what you have already tried doing, we're not here to do things for you: only to help you do it. Might I also suggest that - if possible - you create the filters on the server (PHP, SQL)? It would be much better for the user as the downloaded data will be significantly smaller. Commented Nov 8, 2015 at 19:49
  • Thanks, I added what I tried Commented Nov 8, 2015 at 19:54

2 Answers 2

1

It is possible to create object with categories. As a result all entries can be accessed by category name and you do not need to sort them to have unique titles:

var posts = dataFetched.posts;
var cat = {};

posts.forEach(
    function(p) {
        p.categories.forEach(            
            function(c) {
                if (!cat[c.title])
                    cat[c.title] = [];
                cat[c.title].push(p.title);
            });
    });

console.log(cat);

Output for your example:

Object {Law: Array[1], Business: Array[1], Technology: Array[2]}

Each category title is a key in this object and the arrays of posts are values of those keys.

Sign up to request clarification or add additional context in comments.

Comments

1

The output example you showed is wrong, in JS there's no object like

[Category1: {Post_titleA, PostTitleB, PostTitleC}, Category2: {PostTileF, PostTileX}, etc ]

The most similar thing you can get is a JSON object like this:

{
  "Category1" : ["Post_titleA", "PostTitleB", "PostTitleC"],
  "Category2" : ["PostTileF", "PostTileX"],
  //etc..
}

In order to achieve this, you can use the following function:

function getTitlesByCategory (json) {
    var result = {}
    json.posts.map(function (post) {
        post.categories.map(function (category) {
            result[category.title] = result[category.title] || [];
            result[category.title].push(post.title);
        });
    });

    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.