首页 > 解决方案 > 从另一个对象插入嵌套属性

问题描述

我有两个数组metaObjectsjustObjects.

两个数组中的这些对象具有id共同的属性。

我想创建一个新数组,它结合了不同数组中对象的属性

const metaObjects = [
  {
    id: 1,
    metaProp: "metaProp1"
  },
  {
    id: 2,
    metaProp: "metaProp2"
  }
];

const justObjects = [
  {
    id: 1,
    justProp: "justProp1"
  },
  {
    id: 2,
    justProp: "justProp2"
  }
];

这是我期待的结果

const result= [
    {
      id: 1,
      metaProp: "metaProp1",
      justProp: "justProp1"
    },
    {
      id: 2,
      metaProp: "metaProp2",
      justProp: "justProp2"
    }
  ];

我试图map of map实现这一目标

const combinedObject = justObjects.map(_w => {
  return metaObjects.map(_m => {
    if (_w.id === _m.id) {
      return { ..._m, ..._w };
    }
  });
}, metaObjects);

console.log(combinedObject);

但我收到以下错误

[ [ { id: 1, metaProp: 'metaProp1', justProp: 'justProp1' },
    undefined ],
  [ undefined,
    { id: 2, metaProp: 'metaProp2', justProp: 'justProp2' } ] ]

我不确定为什么每个数组undefined在内部数组中都有一个。
我还需要展平阵列,使它们接近上面的预期结果。

我听说过lensramda 的可组合功能

可以在这里使用吗?

标签: javascriptramda.js

解决方案


这与 customcommander 的答案非常相似,但选择使用groupByandvalues而不是sortByand groupWith。这对我来说更合乎逻辑,尤其是避免不必要的sort电话。

const {pipe, concat, groupBy, prop, values, map, mergeAll} = R

const joinOnId = pipe
  ( concat
  , groupBy (prop ('id'))
  , values
  , map (mergeAll)
  )

const metaObjects = 
  [ { id: 1, metaProp: "metaProp1" }
  , { id: 2, metaProp: "metaProp2" }
  , { id: 3, metaProp: "metaProp3" }  // unique to `meta`
  ]

const justObjects = 
  [ { id: 1, justProp: "justProp1" }
  , { id: 2, justProp: "justProp2" }
  , { id: 4, justProp: "justProp4" }  // unique to `just`
  ]

console.log 
  ( joinOnId (metaObjects, justObjects)
  )
.as-console-wrapper {
  max-height: 100vh !important;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

请注意,这可以很容易地调整以接受不同的属性名称:

const joinOn = (propName) =>
  pipe
    ( concat
    , groupBy (prop (propName))
    , values
    , map (mergeAll)
    )
// ...
const joinOnId = joinOn ('id')

或使用任何常见的密钥生成功能:

const joinOn = (keyFn) =>
  pipe
    ( concat
    , groupBy (keyFn)
    , values
    , map (mergeAll)
    )
// ...
const joinOnId = joinOn (prop ('id'))

推荐阅读