我有一个对象数组。每个对象中还有另一个数组。
结构:
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/