使用map find和function覆盖数组中的对象

时间:2018-01-13 02:27:22

标签: javascript arrays object ecmascript-6

人,

我在练习.map和.find。 我想映射arr1并在id匹配时用arr2覆盖此(arr1)中的每个对象。

<script>

const arr1 = [
  {id: '1', name: 'A', surName: 'A', age: 30},
  {id: '2', name: 'B', surName: 'B', age: 40},
  {id: '3', name: 'C', surName: 'C', age: 50}
];

const arr2 = [
  {id: '1', name: 'D', surName: 'D', age: 60, nickName: 'DD'},
  {id: '5', name: 'E', surName: 'E', age: 70, nickName: 'EE'},
  {id: '3', name: 'F', surName: 'F', age: 80, nickName: 'FF'}
];


let newArr = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

console.log(newArr);

</script>

结果:

0: {…}
age: 60
id: "1"
name: "D"
nickName: "DD"
surName: "D"

1: {…}
age: 40
id: "2"
name: "B"
surName: "B"

2: {…}
age: 80
id: "3"
name: "F"
nickName: "FF"
surName: "F"

但是,我想为不匹配的

添加值为'none'的属性nickName
1: {…}
age: 40
id: "2"
name: "B"
surName: "B"

为结果数组:newArr

我真的被困了。我找不到方法。作为appremtice我会感激帮助。 非常感谢

3 个答案:

答案 0 :(得分:2)

nickName不存在于另一个阵列中时,您可以使用ID分配默认值const arr1 = [{id: '1', name: 'A', surName: 'A', age: 30},{id: '2', name: 'B', surName: 'B', age: 40},{id: '3', name: 'C', surName: 'C', age: 50}], arr2 = [{id: '1', name: 'D', surName: 'D', age: 60, nickName: 'DD'},{id: '5', name: 'E', surName: 'E', age: 70, nickName: 'EE'},{id: '3', name: 'F', surName: 'F', age: 80, nickName: 'FF'}]; var result = arr1.map(o => { var {nickName} = arr2.find(({id}) => id === o.id) || {nickName: 'none'}; return Object.assign({}, o, {nickName}); }); console.log(result);

&#13;
&#13;
Set-Variable -name EPSILON -value ([double]0.00001) #-option Constant
function Is-Same {
    Param(
    [Parameter(Mandatory = $true)] [double]$a,
    [Parameter(Mandatory = $true)] [double]$b
    )
    #return $a - $b;
    return [math]::abs($a - $b) -le $EPSILON;
}

Is-Same 1.000001 1.0000
Is-Same 1.00001 1.0000
Is-Same 1.0001 1.0000
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于集nickName = none,您需要更改||的{​​{1}}。那是因为在那个操作中你要问的是这些元素是否匹配,或者(||)元素&&是否存在。因此,您需要更改它,否则您的所有元素都将通过语句。我尝试过做这样的事情。

obj

答案 2 :(得分:0)

const arr1 = [
  {id: '1', name: 'A', surName: 'A', age: 30},
  {id: '2', name: 'B', surName: 'B', age: 40},
  {id: '3', name: 'C', surName: 'C', age: 50}
];

const arr2 = [
  {id: '1', name: 'D', surName: 'D', age: 60, nickName: 'DD'},
  {id: '5', name: 'E', surName: 'E', age: 70, nickName: 'EE'},
  {id: '3', name: 'F', surName: 'F', age: 80, nickName: 'FF'}
];


let newArr = arr1.map(obj => {
  const match = arr2.find(o => o.id === obj.id)
  return {
    ...obj,
    nickName: match ? match.nickName : 'none'
  }
});

console.log(newArr);
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>