按数组内容过滤/选择 javascript 对象

roa*_*oad 2 javascript arrays json

我正在尝试过滤这些 Javascript 对象:

   A= [{
      asset_bubble: 17,
      biodiversity_loss: 15,
      code: "CH",
      critical_information: 14,
      cyber_attacks: 19,
      data_fraud: 13,
      deflation: 4,
      energy: 18,
      extreme_weather: 12,
      change_adaptation: 9,
      infrastructure: 33
   },
   {
     asset_bubble: 4,
     biodiversity_loss: 7,
     code: "TZ"
     critical_information: 9,
     cyber_attacks: 9,
     data_fraud: 10,
     deflation: 3,
     energy: 1,
     extreme_weather: 2,
     change_adaptation: 7
     infrastructure: 3
}]
Run Code Online (Sandbox Code Playgroud)

通过这个数组:

array=["data_fraud","change_adaptation", "deflation","code"]
Run Code Online (Sandbox Code Playgroud)

我正在寻找的结果是:

B= [{     code: "CH",
          data_fraud: 13,
          deflation: 4,
          change_adaptation: 9
       },
       {
         code: "TZ"
         data_fraud: 10,
         deflation: 3,
         change_adaptation: 7
    }]
Run Code Online (Sandbox Code Playgroud)

我已经这样做了:

B = A.map(({ ...array }) => ({ ...array }))
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。我知道 map 应该完成这项工作,但是如何列出要过滤掉的对象的字段?

Der*_*ang 5

Array.map回调内部,您可以将array变量值映射到[key, item[key]]对,并从该二维数组中,您可以使用Object.fromEntries如下方式生成对象。

const A = [{
  asset_bubble: 17,
  biodiversity_loss: 15,
  code: "CH",
  critical_information: 14,
  cyber_attacks: 19,
  data_fraud: 13,
  deflation: 4,
  energy: 18,
  extreme_weather: 12,
  change_adaptation: 9,
  infrastructure: 33
}, {
  asset_bubble: 4,
  biodiversity_loss: 7,
  code: "TZ",
  critical_information: 9,
  cyber_attacks: 9,
  data_fraud: 10,
  deflation: 3,
  energy: 1,
  extreme_weather: 2,
  change_adaptation: 7,
  infrastructure: 3
}];

const array = ["data_fraud","change_adaptation", "deflation","code"];

const B = A.map((item) => (
  Object.fromEntries(array.map((key) => ([key, item[key]])))
));
console.log(B);
Run Code Online (Sandbox Code Playgroud)