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

问题描述

标题很长,所以我将通过示例来解释问题。我有一组对象:

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

然后我有一个这样的对象数组:

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

现在我想将 myObjects 数组转换为新数组,以便单个对象仅包含 myTemplate 中每个对象的 desiredProperty 中列出的属性。 结果应该是这样的:

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

如何实现这一目标?

解决方法

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

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)
)

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

,

以下代码创建了一个 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);