首页 > 解决方案 > 从对象数组中过滤一些对象

问题描述

我有一个对象数组。我正在尝试从数组中过滤一些对象并使用以下内容获取一个新数组。

[
  {
    "userId": 1,
    "title": "title 1",
    "body": "Body for user 1",
    "address": {
      "country": "Germany",
      "state": "State1"
    },
    "phone": 1234
  },
  {
    "userId": 2,
    "title": "title 2",
    "body": "Body for user 2",
    "address": {
      "country": "Canada",
      "state": "State2"
    },
    "phone": 4321
  }
]

我如何过滤数组并在没有addressand的情况下获取新数组phone。任何帮助表示赞赏。谢谢

标签: javascriptarrays

解决方案


您可以使用.map()和对象解构:

let data = [
    {"userId": 1, "title": "title 1", "body": "Body for user 1", "address": {"country": "Germany", "state": "State1"}, "phone": 1234},
    {"userId": 2, "title": "title 2", "body": "Body for user 2", "address": { "country": "Canada", "state": "State2"}, "phone": 4321}
];

let result = data.map(({address, phone, ...rest}) => rest);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

文件:


推荐阅读