【发布时间】:2017-12-14 13:37:41
【问题描述】:
我想合并两个对象数组。这些对象具有相同的结构,但其中一个缺少 hide 属性。我想将 hide 属性的值从一个对象复制到另一个缺少此属性的对象。重要的是我不想改变这些数组中的任何一个!
第一个数组是这样的(注意有 hide 属性):
let first_array = [
{
name: 'John',
age: 40,
hide: true,
childs: [
{
name: 'Alice',
age: 20,
hide: false,
childs: [
{
name: 'Mike',
age: 2,
hide: true
}
]
}
]
},
{
name: 'Peter',
age: 40,
hide: true,
childs: [
{
name: 'Andrew',
age: 20,
hide: true,
childs: [
{
name: 'Jessica',
age: 2,
hide: true
}
]
}
]
}
]
第二个数组看起来几乎一样!唯一缺少的是隐藏属性。
let second_array = [
{
name: 'John',
age: 40,
childs: [
{
name: 'Alice',
age: 20,
childs: [
{
name: 'Mike',
age: 2,
}
]
}
]
},
{
name: 'Peter',
age: 40,
childs: [
{
name: 'Andrew',
age: 20,
childs: [
{
name: 'Jessica',
age: 2,
}
]
}
]
}
]
现在,我想创建一个新数组,其中每个对象中都有隐藏属性。
我知道如何以 imperative 的方式递归地执行此操作,但不幸的是我正在改变数据 - 我不想这样做。
function getHideProperty(first, second) {
for (let i = 0; i < second.length; i++) {
for (let j = 0; j < first.length; j++) {
if (second[i].name === first[j].name) {
second[i].hide = first[j].hide
if (second[i].childs) {
second[i].childs = getHideProperty(first[j].childs, second[i].childs)
}
}
}
}
return second
}
现在我可以创建包含合并对象的新数组:
const newArray = getHideProperty(second_array, first_array)
现在,second_array 中的每个对象都有 hide 属性。但我改变了数组:(
如何在不改变数组的情况下达到这样的结果?
【问题讨论】:
-
从技术上讲,当然,您不会改变数组。您正在改变数组引用的对象。就解决方案的思考而言,这很重要。
-
所谓的mutating是指某个数组的值一开始是X,传给函数后,这个数组的值就不再是X了。变异了
-
好吧,同样,它不是(数组中的值 - references 对象 - 在您的示例中未更改),但它仅在以下方面很重要帮助了解避免它需要什么:创建新对象(和新数组)。 :-)
标签: javascript dictionary filter functional-programming reduce