首页 文章

更新对象属性并使用Reduce Javascript将它们添加到新的Arr中

提问于
浏览
0

我试图在具有键值对属性的对象数组中使用reduce in addKeyAndValue函数,在每个对象中添加一个新的键值对并将其返回到新数组 . addKeyAndValue函数接收三个参数arr,键和要在数组中的每个对象中一起添加的值 . 然后我在Reduce回调中使用push将数组中的对象推送到累加器中的新数组,并使用括号表示法更新新的键和值 .

var arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}]

function addKeyAndValue(arr, key, value){
    return arr.reduce(function(acc, nextValue, idx){
        console.log(next);
        acc.push(nextValue[key] = value);
        return acc;
    },[]);
}

预期的结果应该是:

addKeyAndValue(arr, 'title', 'Instructor') // 
      [
        {title: 'Instructor', name: 'Alonso'}, 
        {title: 'Instructor', name: 'James'}, 
        {title: 'Instructor', name: 'Chris'}, 
        {title: 'Instructor', name: 'Steve'}
       ]

但是,我在Chrome开发者控制台中获得的结果是:

(4) ["Instructor", "Instructor", "Instructor", "Instructor"]
0:"Instructor"
1:"Instructor"
2:"Instructor"
3:"Instructor"
length:4
__proto__:Array(0)

我想知道为什么Value通过 nextValue[key] 覆盖整个对象并以字符串形式返回 . 当我尝试只推动新数组中的现有对象时,它工作正常,但是当按下 nextValue[key] 时,它变为未定义,当执行上述 nextValue[key] = value 时,它会覆盖对象,从而导致只有 instructor 字符串的新数组 . 我有点困惑,因为我期待不同的结果 .

在nextValue上使用括号符号 nextValue[key] ,这是由reduce方法中的回调迭代的数组中的每个对象,我认为在这种情况下会添加一个新的键属性 "title" ,其指定的值为 "instructor" .

任何帮助将不胜感激,谢谢:) .

2 回答

  • 1

    您的 push 参数仅导致 value 被推送,而不是对象 . 如果你真的想在一个表达式中使用逗号运算符,你可以解决这个问题:

    acc.push((nextValue[key] = value, nextValue));
    

    但如果单独执行它可能更具可读性:

    nextValue[key] = value;
    acc.push(nextValue);
    
  • 2

    您将赋值的结果推送到数组中,而不是对象 .

    由于结果 nextValue[key] = valuevalue . 使用 acc.push(nextValue[key] = value); 就像在做 acc.push(value) .

    由于您要更新每个对象,use Array#map以迭代数组 . 使用Object#assign克隆每个对象(以防止改变原始对象),并添加属性:

    var arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}];
    
    function addKeyAndValue(arr, key, value){
      return arr.map(function(obj){
        var clone = Object.assign({}, obj);
        clone[key] = value;
        return clone;
      });
    }
    
    var result = addKeyAndValue(arr, 'title', 'Instructor');
    
    console.log(result);
    

    The ES6 version

    const arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}];
    
    function addKeyAndValue(arr, key, value){
      return arr.map((obj) => Object.assign({ [key]: value }, obj));
    }
    
    const result = addKeyAndValue(arr, 'title', 'Instructor');
    
    console.log(result);
    

相关问题