Search code examples
javascriptarraysobjectmappingreducing

Get specific data from an array of object and convert to object


I have an array of objects. In the each object is also another array.

Structure:

function getData() {
  return [
    {
      _id: 1,
      tags: ["tomato", "butter", "milk"],
      title: "How to make soup?",
      category: "Food"
    },
    {
      _id: 2,
      tags: ["pepper", "salt", "basil"],
       title: "How to use herbs?",
      category: "Herbs"
    },
  ];
}

I am trying to get from the array: tags and category. Output should be:

{
      tags: ["tomato", "butter", "milk"],
      category: "Food"
},
 {
      tags: ["pepper", "salt", "basil"],
      category: "Herbs"
},

I tried a few concepts, but result is not as I wish :(

For example:

function getTagsandCategory() {
  const tags = getData()
    .map(post => {post.tags, post.category});

 console.log(tags);
}

getTagsandCategory(); 
// Output: [undefined, undefined]

or better (but unfortunately not ideal)

 function getTagsandCategory() {
  const tags = getData()
    .map(post => [post.tags, post.category]);

 console.log(tags);
}

getTagsandCategory();
// Output: [["tomato", "butter", "milk"], "Food"]

Do you have please any idea, how to achieve that? Thank you!


Solution

  • You need to use Array.prototype.map()

    const data = [
        {
          _id: 1,
          tags: ["tomato", "butter", "milk"],
          title: "How to make soup?",
          category: "Food"
        },
        {
          _id: 2,
          tags: ["pepper", "salt", "basil"],
           title: "How to use herbs?",
          category: "Herbs"
        },
      ];
      
      const output = data.map(obj => ({ tags: obj.tags, category: obj.category }));
      
      console.log(output);