【发布时间】:2020-11-12 00:28:29
【问题描述】:
我现在有两个对象(一个是 JSON Schema,一个是来自我们 API 的响应),我想合并它们以便更好地映射和使用。
架构如下所示:
// schema
{
key: {
description: "foo",
properties: {
values: {
title: "foo",
type: "Array"
},
type: "string"
},
type: "object"
},
foo: {
title: "title",
description: "bar"
},
bar: {
title: "title",
description: "who"
}
}
而我的响应对象是这样的:
// response
{
key: {
values: [0, 1]
type: "point"
},
foo: null,
bar: "some string"
}
我只想合并这两个对象,但使用 const mergedObject = {...schema, ...response} 会导致覆盖值。
所以我想要的结果将包含一个名为value 的新对象道具或包含response 对象值的东西:
{
key: {
value: {
values: [0, 1],
type: "point",
},
description: "foo",
properties: {
values: {
title: "foo",
type: "Array"
},
type: "string"
},
type: "object"
},
foo: {
value: null,
title: "title",
description: "bar"
},
bar: {
value: "some string",
title: "title",
description: "who"
}
}
使用扩展运算符是否可行?我在这里找不到合适的解决方案,因为 lodashs assign 或 assignIn 也不提供该功能。
我也试过这个功能:
function merge (...objs) =>
[...objs].reduce(
(acc, obj) =>
Object.keys(obj).reduce((a, k) => {
acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
return acc;
}, {}),
{}
);
但它给了我
{
bar: [
{
title: "title",
description: "who"
},
"some string",
],
foo: [
{
title: "title",
description: "bar",
},
null
],
key: [
{
description: "foo",
properties: {
values: {
title: "foo",
type: "Array"
},
type: "string"
},
type: "object"
},
{
values: [0, 1]
type: "point"
}
]
}
这也不是我想要的。
感谢任何帮助,谢谢!
【问题讨论】:
标签: javascript object functional-programming