【发布时间】:2017-01-21 08:35:29
【问题描述】:
过滤数组在这里被问了很多,但我发现的问题和答案都没有考虑到我需要的两个条件:
1. 不改变对象。
2.使用es6(ecmascript2015)及以上版本。
3. 得到一个新的数组来保存被覆盖的对象和值。
我实际上对我的问题的一部分有一个答案,那就是如何过滤,但感觉像是一种 hack 而不是真正的解决方案,第二部分是如何通过第二个数组的更改来获取完整的原始数组但不会改变对象。
这是我的代码,如您所见,我明确地分配了{dirty:true},而不是从它自己的数组中传递对象:
const docPositions = [
{
active : false,
dirty : false,
key : "somekey2"
},
{
active : false,
dirty : false,
key : "somekey1"
},
{
active : false,
dirty : false,
key : "somekey4"
},
{
active : false,
dirty : false,
key : "somekey3"
}
]
const dirtyPositions = [
{
active : false,
dirty : true,
key : "somekey1"
},
{
active : false,
dirty : true,
key : "somekey3"
}
]
let result = docPositions.filter(x=> dirtyPositions.some(y=>y.key == x.key))
.map(o=> Object.assign({},o,{dirty:true}));
console.log(result);
结果:
Array [
Object {
"active": false,
"dirty": true,
"key": "somekey1"
},
Object {
"active": false,
"dirty": true,
"key": "somekey3"
}
]
想要的结果:
Array [
{
active : false,
dirty : false,
key : "somekey2"
},
{
active : false,
dirty : true,
key : "somekey1"
},
{
active : false,
dirty : false,
key : "somekey4"
},
{
active : false,
dirty : true,
key : "somekey3"
}
]
【问题讨论】:
-
您最后列出的输出不是代码产生的。您可能没有从实际输出中复制它。提示:
dirty在输出中应该是true,而active不应该。 -
如果您想将
dirty设置为 true,我认为您无法避免额外的映射。
标签: javascript arrays ecmascript-6 immutability