【问题标题】:Getting only requested item from every object Javascript [duplicate]从每个对象Javascript中仅获取请求的项目[重复]
【发布时间】:2021-05-09 16:24:01
【问题描述】:

我想弄清楚我是否只能从后端向前端发送相关的 javascript 信息,因为我想在我的前端发出请求时隐藏 ID 等内容。

为了更清楚地说明问题,这里有一个虚拟代码。

[
 {
  "_id": "215874514845452155",
  "greeting":"Hello there"
 },
 {
  "_id": "181474545841541515",
  "greeting": "General Kenobi"
 },
]

请求时,我想得到如下结果:

[
 {
  "greeting": "Hello there"
 },
 {
  "greeting": "General Kenobi"
 },
]

我还在学习东西,我知道循环功能,但我想知道它是否有一些巧妙的技巧。我来自 R 编程,我们讨厌循环。

【问题讨论】:

  • 使用 Array.map()
  • 我想这就是你想要的:stackoverflow.com/questions/9598505/…
  • array.map(({ greeting }) => ({ greeting }))
  • 瞧!这很好用。谢谢大家!
  • 仅供参考,如果我想要多个项目。我将如何使用地图功能?

标签: javascript arrays json parsing


【解决方案1】:

使用Array.prototype.map:

const input = [
 {
  "_id": "215874514845452155",
  "greeting":"Hello there",
  "other":"foo"
 },
 {
  "_id": "181474545841541515",
  "greeting": "General Kenobi",
  "other":"bar"
 },
];

const result = input.map(({greeting,other}) => ({greeting,other}));
console.log(result);

上面是写这个的简写方式:

const input = [
 {
  "_id": "215874514845452155",
  "greeting":"Hello there",
  "other":"foo"
 },
 {
  "_id": "181474545841541515",
  "greeting": "General Kenobi",
  "other":"bar"
 },
];

const result = input.map(x => {
  return {
    greeting: x.greeting,
    other: x.other
  }
});
console.log(result);

【讨论】:

  • @ashishbajaj 如果您不习惯解构/对象创建,可能很难理解它在做什么。检查更新
  • 是的,我明白了。新的更新也有效,但我想我会去解构。看起来很整洁。
  • @ashishbajaj 第二个有很多重复,这就是为什么破坏路线更好
猜你喜欢
  • 1970-01-01
  • 2019-07-25
  • 2021-09-13
  • 2019-03-29
  • 2021-12-25
  • 2023-03-12
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多