【问题标题】:Loop through nested json array to create new array循环遍历嵌套的 json 数组以创建新数组
【发布时间】:2019-04-02 20:49:40
【问题描述】:

我正在开发一个 lambda 函数,该函数将 GETs 来自一个 API 的数据和 POSTs 发送到另一个 API。数据是具有属性的联系人列表,例如名字、姓氏、电子邮件等。

JSON 输出包含太多我不需要的属性。请参阅下面的代码示例(实际代码包含更多属性和嵌套数组/对象)。

{
  "contacts": [
      {
          "addedAt": 1532803458796,
          "vid": 101
      }
   ],
  "merge-audits": [],
  "properties": {
       "first-name": {
          "value":"hello"
        },
        "last-name": {
          "value":"there"
        },
        "email": {
          "value":"hello@there.com"
        }
... 
...
}

如何循环每个 JSON 对象来创建一个新的、更简单的 JSON 数组,如下所示:

[
  {
    "email": "example@example.com",
    "first_name": "",
    "last_name": "User"
  },
  {
    "email": "example2@example.com",
    "first_name": "Example",
    "last_name": "User"
  }
]

提前感谢您的帮助。

【问题讨论】:

  • JSON 是文本。当您说“原始 JSON”时,您似乎真的在强调它是 JSON……但是是吗?还是我们从 JavaScript 对象开始?
  • 您的 json 是否有多个称为属性的键?

标签: javascript arrays json javascript-objects


【解决方案1】:

试试

json.map( x => ({
  email:      x.properties.email.value,
  first_name: x.properties['first-name'].value,
  last_name:  x.properties['last-name'].value,
}));

let json = [
{
  "contacts": [{
    "addedAt": 1532803458796,
    "vid": 101
  }],
  "merge-audits": [],
  "properties": {
    "first-name": {
      "value": "hello"
    },
    "last-name": {
      "value": "there",
    },
    "email": {
      "value": "hello@there.com"
    }
  }
},
{
  "contacts": [{
    "addedAt": 1532803458796,
    "vid": 101
  }],
  "merge-audits": [],
  "properties": {
    "first-name": {
      "value": "Tom"
    },
    "last-name": {
      "value": "Smith",
    },
    "email": {
      "value": "tom@smith.com"
    }
  }
}
]

let r = json.map(x => ({
  email:      x.properties.email.value,
  first_name: x.properties['first-name'].value,
  last_name:  x.properties['last-name'].value,
}));

console.log(r);

【讨论】:

  • 经过测试,完美运行,非常高效,谢谢!
【解决方案2】:

您可以将destructuring assignment 用于对象,将short hand properties 用于映射。

var data = [{ contacts: [{ addedAt: 1532803458796, vid: 101 }], "merge-audits": [], properties: { "first-name": { value: "hello" }, "last-name": { value: "there" }, email: { value: "hello@there.com" } } }],
    result = data.map(({ properties: {
        'first-name': { value: first_name },
        'last-name': { value: last_name },
         email: { value: email }
    } }) => ({ first_name, last_name, email }));

console.log(result);

【讨论】:

  • 您的解决方案也会产生相同的结果。感谢您提供更多信息。这也适用于数据变量中的多个对象吗?
  • 确实如此,因为数据是一个数组,每个相同的组织对象都会被转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2021-05-31
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多