1

Code after request:

var posts = [
  {  
    "id":268,
    "title":{  
       "rendered":"Koala"
    },
    "categories":[2]
  }
]

var categories = [  
  {  
    "id":2,
    "name":"Animals"
  },
  {  
    "id":3,
    "name":"Birds"
  },
]

Goal: - Create a function that takes posts.categories value and replace it with matching id of categories.name.

Result:

var posts = [
  {  
    "id":268,
    "title":{  
       "rendered":"Koala"
    },
    "categories":["Animals"]
  }
]

I have searched around, but could not find a solution. Can someone please help me with this issue?

2 Answers 2

0

Here is a way to do that :

function setPostsCategories(posts, categories) {
  posts.forEach(function(post) {
    var cats = []
    post.categories.forEach(function(categorie) {     
      cats.push(categories.find(function(a) {
        return a.id == categorie
      }).name);
    })
    post.categories = cats
  })
  return posts
}

console.log("post",setPostsCategories(posts, categories));

See demo fiddle here. If you need to support IE, check here to define Array.find.

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

Comments

0

My first approach would be to the ids of the categorie as location of the categories array.

//Let the position be the corresponding id
var categories = [
  {
    "name":"Humans"
  },
  {
    "name":"Insects"
  },
  {
    "name":"Animals"
  },
  {
    "name":"Birds"
  },
]

var posts = [
  {  
    "id":268,
    "title":{  
       "rendered":"Koala"
    },
    // Requests all data from that categorie posistion
    "categories":categories[2]
  }
]

console.log(posts);

The approach you request is this:

function FindId(obj, id) {
  let max = obj.length;
  // Loop to items.
  for (let i = 0; i < max; i++)
    // Check if id is the same.
    if (obj[i]["id"] == id)
      // Returns right name.
      return obj[i]["name"];
}

var categories = [  
  {  
    "id":2,
    "name":"Animals"
  },
  {  
    "id":3,
    "name":"Birds"
  },
]

var posts = [
  {  
    "id":268,
    "title":{  
       "rendered":"Koala"
    },
    "categories":FindId(categories, 2)
  }
]

console.log(posts);

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.