javascript - 从对象数组中获取特定数据并转换为对象

标签 javascript arrays object mapping reducing

我有一个对象数组。每个对象中还有另一个数组。

结构:

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"
    },
  ];
}

我试图从数组中获取:标签和类别。输出应该是:

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

我尝试了一些概念,但结果并不如我所愿:(

例如:

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

 console.log(tags);
}

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

或更好(但不幸的是不理想)

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

 console.log(tags);
}

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

请问您有什么想法,如何实现?谢谢!

最佳答案

你需要使用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);

关于javascript - 从对象数组中获取特定数据并转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182332/

相关文章:

python - 在 PYTHON 中用另一个数字替换一个数字

Javascript DOM ChildNodes 属性未捕获所有子节点

javascript - Angularjs 与 packery.js 可拖动

javascript - 从对象属性递归生成文件路径

javascript - 冒泡排序 - 为什么需要额外的循环

javascript - 如何循环遍历Object,然后获取IndexOf字符串,例如A,B..然后如果A=1,b=2则转换为值

javascript - 将对象内部的对象加载到 html 表中

swift - 快速在标签中显示数组

javascript - 如何在测试中伪造 Bluebird 的计时器?

javascript - href 内的输出变量 - Javascript