javascript - 从另一个对象插入嵌套属性
问题描述
我有两个数组metaObjects
和justObjects
.
两个数组中的这些对象具有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
在内部数组中都有一个。
我还需要展平阵列,使它们接近上面的预期结果。
我听说过lens
ramda 的可组合功能
可以在这里使用吗?
解决方案
这与 customcommander 的答案非常相似,但选择使用groupBy
andvalues
而不是sortBy
and 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'))
推荐阅读
- c# - 在 EF 代码中交叉包含相同的表关系引发错误违反多重性约束
- jsf - Concatenation inside a JSF expression
- javascript - How to stop scroll event when path application changed?
- java - IllegalAccessError 到方法 copyOfRange Kotlin
- php - PhpStorm 缩进设置(与 GitHub 显示不同)
- elasticsearch - 使用 Kafka Connect Elasticsearch 连接器的消息顺序
- ruby-on-rails - 使用 heroku 调度程序更改测功机大小
- java - 如果状态为成功,则 else 也阻止在 android 中执行
- docker - CircleCI docker撰写权限被拒绝?
- javascript - 使用 JavaScript 计算 HTML 表格中的单元格数