【问题标题】:Get the value of a key value pair in an object in an array [duplicate]获取数组中对象中键值对的值[重复]
【发布时间】:2021-05-21 23:23:07
【问题描述】:

我想在一个新数组中获取属性value 的值。对于以下示例,结果将是:["Plumbing", "Electrical", "Fencing"]

const arr = [
  { label: "Plumbing", value: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

我的意思是:newArray = currentArray forEach Get Value

【问题讨论】:

  • 使用arr.map(o => o.value)
  • 答案如下。你应该接受就是答案。

标签: javascript


【解决方案1】:

您可以使用map轻松获取所有label的值

const arr = [
  { label: "Plumbing", value: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

const result = arr.map((o) => o.value);
console.log(result);

你也可以解构让它更简洁

const result = arr.map(({ value }) => value);

const arr = [
  { label: "Plumbing", value: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

const result = arr.map(({ value }) => value);
console.log(result);

【讨论】:

  • 嗯...在这种情况下,我不建议减少 OP。 Map 是这种情况下的正确函子,无论如何,reduce 可能会混淆 OP
  • 这就是我在您发表评论之前将其删除的原因。谢谢你的建议。呵呵
  • 你是对的,这就是我支持你的原因。用我的语言,我们说“既然可以让它变得复杂,为什么要让它变得简单”:)
  • 无论如何,这显然是重复的家伙,让我们轻松回答
【解决方案2】:

您可以使用 forEach 将值添加到新数组中,如下所示:

const arr = [
  { value: "Plumbing", label: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

var newArr = []
arr.forEach(e => newArr.push(e.value))

console.log(newArr)

或者就像@decpk 在评论中说的,你可以像这样简单地使用map()

const arr = [
  { value: "Plumbing", label: "Plumbing" },
  { label: "Electrical", value: "Electrical" },
  { label: "Fencing", value: "Fencing" },
];

var newArr = arr.map(e => e.value)

console.log(newArr)

【讨论】:

  • 当你有map默认返回新数组的结果时,为什么要使用forEach
猜你喜欢
  • 2018-10-03
  • 1970-01-01
  • 2020-11-11
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多