[英]Loop through two array and based on condition change the property value not working
I have two arrays with some common property.我有两个具有一些共同属性的数组。 I use filter and if Id is equal then change one of the value, here for example email.我使用过滤器,如果 Id 相等,则更改其中一个值,例如电子邮件。 I use spread operator for the same.我也使用扩展运算符。 But it is not working.但它不起作用。 However when I console log before returning it shows the update value.但是,当我在返回之前控制台日志时,它会显示更新值。 Also if I change using assignment operator then its working.此外,如果我使用赋值运算符进行更改,那么它的工作原理。 Can somebody let me know why is spread operator not working or I am missing some concept.有人可以让我知道为什么传播运算符不起作用或者我缺少一些概念。 Below is sample code下面是示例代码
var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];
var result2 = [
{id:2, name:'John', email:'johnny@example.com',fullName:'Test1'},
{id:4, name:'Bobby', email:'bobby@example.com',fulname:'Test2'}
];
var result = result2.filter(function(x){
return result1.filter(function(y){
if(x.id === y.id){
console.log( {...x,email:y.name})
return {...x,email:y.name}
// x.email=y.name
}
});
})
console.log(result)
The filter
function should return a boolean and it's not meant to edit objects. filter
函数应该返回一个布尔值,它并不意味着编辑对象。
Try to map
the first array and find
their values in the other, if the value is present return the edited object:尝试map
第一个数组并在另一个数组中find
它们的值,如果值存在则返回编辑后的对象:
var result1 = [ { id: 1, name: 'Sandra', type: 'user', username: 'sandra' }, { id: 2, name: 'John', type: 'admin', username: 'johnny2' }, { id: 3, name: 'Peter', type: 'user', username: 'pete' }, { id: 4, name: 'Bobby', type: 'user', username: 'be_bob' }, ]; var result2 = [ { id: 2, name: 'John', email: 'johnny@example.com', fullName: 'Test1' }, { id: 4, name: 'Bobby', email: 'bobby@example.com', fulname: 'Test2' }, ]; const result = result2.map((x) => { const y = result1.find(value => x.id === value.id); if (y) return { ...x, email: y.name }; return x; }) console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.