使用.map影响整个对象(使其未定义)而不是更新属性

Cra*_*ley 3 javascript ecmascript-6

当我做:

csvParse(txtString, {columns: true})
Run Code Online (Sandbox Code Playgroud)

我得到一个对象数组,在此我想为每个对象更新某个属性.

但所有发生的事情都是对象变得不确定.

这完全符合我的预期:

let x = [{
  y: 123,
  z: 'abc'
}, {
  y: 456,
  z: 'efg'
}, {
  y: 789,
  z: 'hij'
}];

console.log(x);

x.map(x => {
  x.z.toUpperCase();
});
console.log(x); // no changes saved

x.map(x => {
  x.z = x.z.toUpperCase();
});
console.log(x); //now z is uppercase
Run Code Online (Sandbox Code Playgroud)

但是,当我在我的代码中执行相同操作时:

resolve(
  csvParse(txtString, {
    columns: true
  })
  .map(x => {
    x.categories = x.categories
      .replace(regexes.doubleQuotesOrSquareBrackets, '')
      .split(',');
  })
);
Run Code Online (Sandbox Code Playgroud)

结果数组中的每个元素都是未定义的.

Sus*_* -- 5

ES6函数的工作方式是,当存在单个语句时返回计算值,如果有多个语句则需要显式使用 return

在您的情况下,您的单个语句是一个赋值操作.

所以它在技术上回归 undefined

.map(x => {
       x.categories = ...
});
Run Code Online (Sandbox Code Playgroud)

不过是

.map(x => {
       x.categories = ...
       return undefined;
});
Run Code Online (Sandbox Code Playgroud)

要解决它你可以做到

.map(x => {
       x.categories = ...;
       return x.categories;
});
Run Code Online (Sandbox Code Playgroud)

要么

.map(x => {
    ...;
    return x;
});
Run Code Online (Sandbox Code Playgroud)