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

Updating object properties and adding them in a new Arr with Reduce Javascript

我正在尝试在具有键值对属性的对象数组的 addKeyAndValue 函数中使用 reduce,在每个对象中添加一个新的键值对,然后 return 在一个新数组上添加它。 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)

我想知道为什么通过 nextValue[key] 传递的值会覆盖整个对象并 return 只是作为一个字符串。当我尝试将现有对象推送到新数组中时它工作正常但是当推送 nextValue[key] 时它变为未定义并且当执行上述 nextValue[key] = value 时它覆盖对象导致新数组 instructor 字符串。我有点困惑,因为我期待的是不同的结果。

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

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

您正在将赋值结果推入数组,而不是对象。

因为结果 nextValue[key] = valuevalue。使用 acc.push(nextValue[key] = value); 就像 acc.push(value).

由于您要更新每个对象,use Array#map to iterate the array. Clone each object (to prevent mutating the original objects) using 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);

ES6版本

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);

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

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

但是分开写可能会更易读:

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