通过删除不包含在另一个数组中的 object 属性来转换 object 的数组

Transform an array of objects by removing object properties not contained in another array

标题很长,所以我会通过例子来解释这个问题。我有一个数组 objects:

const myObjects = [
   {
      id: 1,
      name: "a",
      stuff: "x"
   },
   {
      id: 2,
      name: "b",
      stuff: "y"
   },
];

然后我有另一个像这样的 object 数组:

const myTemplate=[
   {
      desiredProperty: "name",
      someOtherProperty: "..."
   },
   {
      desiredProperty: "stuff",
      someOtherProperty: "..."
   },
];

现在我想将 myObjects 数组转换为新数组,以便单个 object 仅包含 myTemplate 中每个 object 的 desiredProperty 中列出的属性。 结果应如下所示:

myResult = [
   {
      name: "a",
      stuff: "x"
   },
   {
      name: "b",
      stuff: "y"
   }
]

如何实现?

以下代码创建一个 Set 您要保留的密钥。然后,我们 map 遍历您的 myObjects 数组,只保留 toKeep 集合中的对象键。

const myObjects=[{id:1,name:"a",stuff:"x"},{id:2,name:"b",stuff:"y"}];
const myTemplate=[{desiredProperty:"name",someOtherProperty:"..."},{desiredProperty:"stuff",someOtherProperty:"..."}];

const toKeep = new Set(myTemplate.map(t => t.desiredProperty));

const newObjs = myObjects.map(o => {
  const obj = {};
  for (let key in o) {
    if (toKeep.has(key)) {
      obj[key] = o[key];
    }
  }
  return obj;
});

console.log(newObjs);

这种方法让您可以部分应用模板,针对多组输入取回 运行 的可重用函数:

const convert = (template, keys = new Set (template .map (t => t .desiredProperty))) => (xs) =>
  xs .map (
    (x) => Object .fromEntries (Object .entries (x) .filter (([k, v]) => keys .has (k)))
  )

const myObjects = [{id: 1, name: "a", stuff: "x"}, {id: 2, name: "b", stuff: "y"}]
const myTemplate= [{desiredProperty: "name", someOtherProperty: "..."}, {desiredProperty: "stuff", someOtherProperty: "..."}]

console .log (
  convert (myTemplate) (myObjects)
)

但我同意这里的模板最好表示为要保留的键数组的评论。