在 JavaScript 中获取数组对象中特定的值

3

我试图从结果数组中仅获取标签为onetwo的两个对象。 如何过滤对象数组中的值?有人可以帮忙吗?

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"
  },
]
5个回答

3
你可以使用 filter 来检查标签是否为 "one" 或者(而不是并且)"two",无需使用 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)


1
你想将条件更改为“或”(使用||而不是&&),因为一个特定的元素不能同时具有标签'one' 'two'。

你希望一个特定的元素拥有标签,要么是'one',要么是'two'


1
我认为你想要做这个 -
arr.filter((obj) => obj.label == "one" || obj.label == "two");

0

filter()方法通过提供的函数实现的测试来创建一个新数组,其中包含所有通过测试的元素。

您不必使用map。您可以直接使用filter()过滤您的数组,该方法接受一个函数(该函数将每个数组元素作为参数)并返回仅与函数指定条件匹配的元素的新数组。

您可以按以下方式执行此操作 -

const arr = [{
    value: "1",
    label: "one"
  },
  {
    value: "2",
    label: "two"
  },
  {
    value: "3",
    label: "three"
  },
];


let filtered_arr = arr.filter((obj)=> obj.label==='one' || obj.label==='two');

console.log(filtered_arr)


0
使用 filter 方法:
arr.filter(obj => ((obj.label=="one")||(obj.label=="two")))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接