【问题标题】:Filter json by keys (not by value) [duplicate]按键过滤json(而不是按值)[重复]
【发布时间】:2021-01-18 11:00:33
【问题描述】:

我有这个 json:

json = [{
    "code3": "ALB",
    "asset": 9,
    "biodiversity": 4,
    "infrastructure": 15
}, {
    "code3": "GHN",
    "asset": 4,
    "biodiversity": 5,
    "infrastructure": 5,
}, {
    "code3": "TGO",
    "asset": 3,
    "biodiversity": 6,
    "infrastructure": 7
}]

我正在尝试在 for 循环中将其过滤到此:

result = [{
    "code3": "ALB",
    "asset": 9
}, {
    "code3": "GHN",
    "asset": 4
}, {
    "code3": "TGO",
    "asset": 3
}]

最快的方法是什么。我知道我可以使用 json.forEach(j => del j["infrastructure"] ... 或类似的东西,但我希望通过键 code3, asset 过滤掉

【问题讨论】:

标签: javascript json filter


【解决方案1】:

你可以使用.map:

let json = [
     {
          "code3": "ALB",
          "asset": 9,
          "biodiversity": 4,
          "infrastructure": 15
     },
     {
          "code3": "GHN",
          "asset": 4,
          "biodiversity": 5,
          "infrastructure": 5,
      },
      {
           "code3": "TGO",
           "asset": 3,
           "biodiversity": 6,
           "infrastructure": 7
      }
];

let list = json.map(e => {
     return {
          code3: e.code3,
          asset: e.asset
     }
});

console.log(list);

【讨论】:

  • 更短如.map(({code3, asset}) => ({code3, asset}))
【解决方案2】:

let json = [
     {
          "code3": "ALB",
          "asset": 9,
          "biodiversity": 4,
          "infrastructure": 15
     },
     {
          "code3": "GHN",
          "asset": 4,
          "biodiversity": 5,
          "infrastructure": 5,
      },
      {
           "code3": "TGO",
           "asset": 3,
           "biodiversity": 6,
           "infrastructure": 7
      }
];

let result = json.map(({code3, asset}) => ({code3, asset}));

console.log(result);

一开始这可能会让人感到困惑,所以让我们看看它是如何工作的:

  • .map 方法创建一个新数组,其中包含前一个数组中每个元素的函数输出。
    • 示例:
let nums = [0, 1, 2, 3];
let add1 = n => n + 1;

// The following two statements are equivalent:
nums = [add1(num[0]), add1(num[1]), add1(num[2]), add1(num[3])];
nums = nums.map(add1);
let a = 'foo', b = 42, c = {};
let o = {a, b, c}

// o = { a: 'foo', b: 42, c: {} }

希望将这些部分放在一起本身就很直观。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多