遍历嵌套的json数组以创建新的数组

时间:2019-04-02 20:49:40

标签: javascript arrays json javascript-objects

我正在研究一个lambda函数,该函数GET的数据来自一个API,POST的数据到另一个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"
  }
]

预先感谢您的帮助。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

相关问题