我试图在结果数组中只获取两个对象,标签为 one
和标签为 two
。
如何过滤对象数组中的值。有人可以帮忙吗?
const arr = [{
value: "1",
label: "one"
},
{
value: "2",
label: "two"
},
{
value: "3",
label: "three"
},
];
arr.map((val, index) => val.filter(val.label => val.label === 'one' && val.label === 'two'))
console.log(arr)
我期待下面这样的输出
[{
value: "1",
label: "one"
},
{
value: "2",
label: "two"
},
]
最佳答案
您可以使用 filter
检查标签是“一个”还是(不是和)“两个” (您不需要 map
)。
const arr = [{
value: "1",
label: "one"
},
{
value: "2",
label: "two"
},
{
value: "3",
label: "three"
},
];
const res = arr.filter(val => val.label === 'one' || val.label === 'two');
console.log(res)
如果你想允许多个标签,你可以使用 Set
存储它们,并使用 Set#has
用于过滤。
const arr = [{
value: "1",
label: "one"
},
{
value: "2",
label: "two"
},
{
value: "3",
label: "three"
},
{
value: "4",
label: "four"
},
{
value: "5",
label: "five"
},
{
value: "6",
label: "six"
},
{
value: "7",
label: "seven"
}
];
const allowedLabels = new Set(["one", "two", "four", "seven"]);
const res = arr.filter(val=>allowedLabels.has(val.label));
console.log(res)
关于javascript - 仅获取 JavaScript 对象数组中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62541955/