js -将一个对象合并到一个数组中



我有一个数组,结构如下:

const screens = [
{
name: 'John',
options: {
headerTitle: 'Book Title',
},
},
{
name: 'Bill',
options: {
headerTitle: 'Another title',
},
},
];

和我需要插入到上面的'options:'中的一段数据。我可以随意重塑这些数据。可以是:

const header = {
headerStyle: {
borderBottomWidth: 0.5,
borderColor: 'black',
},
};

header2 = [
{
borderColor: 'red',
borderWidth: 0.5,
},
];

最终目标是:

const screens = [
{
name: 'John',
options: {
headerTitle: 'Book Title',
headerStyle: {
borderColor: 'red',
borderWidth: 0.5,
},
},
{
name: 'Bill',
options: {
headerTitle: 'Another title',
headerStyle: {
bordercolor: 'red',
borderWidth: 0.5,
},
},
];

我一直在谷歌搜索扩展运算符,但我似乎无法将两者合并。

的想法是映射现有的数组到一个新的与您的选项合并

const screens = [{"name":"John","options":{"headerTitle":"Book Title"}},{"name":"Bill","options":{"headerTitle":"Another title"}}]
const header = {
headerStyle: {
borderBottomWidth: 0.5,
borderColor: 'black'
}
}
const merged = screens.map(screen => ({
...screen,
options: {
...screen.options,
...JSON.parse(JSON.stringify(header))
}
}))
console.log(merged)
.as-console-wrapper { max-height: 100% !important; }

这里需要注意的一点是,没有JSON.parse(JSON.stringify(header)),数组中的每个对象将共享相同的headerStyle对象引用。使用扩展语法可能有更简单的方法来破坏对象引用,但是考虑到要合并的对象的潜在动态特性,使用JSON方法是一个方便的包揽一切的方法。

如果这能帮到你。
只是循环数组并附加headerStyle。三个点表示提取数据,意在防止参考。

const screens = [
{
name: 'John',
options: {
headerTitle: 'Book Title',
},
},
{
name: 'Bill',
options: {
headerTitle: 'Another title',
},
},
];
const header = {
headerStyle: {
borderBottomWidth: 0.5,
borderColor: 'black',
},
};
screens.forEach(item=>{item.options['headerStyle']={...header.headerStyle}})
console.log(screens)

最新更新