在Javascript中使用map函数返回新值

1 javascript arrays json object

这是我的json:

[ { gsm: 'gsm',
  firstName: 'firstname',
  lastName: 'lastname' },
{ gsm: '123456789',
  firstName: 'Mohamed',
  lastName: 'Sameer'},
{ gsm: '987654321',
  firstName: 'Hameed',
  lastName: 'Basha'}]
Run Code Online (Sandbox Code Playgroud)

我希望我的最终输出看起来像:

[ { gsm: 'gsm',
  firstName: 'firstname',
  lastName: 'lastname',
  userKey: 'Key1'},
{ gsm: '123456789',
  firstName: 'Mohamed',
  lastName: 'Sameer',
  userKey: 'Key1'},
{ gsm: '987654321',
  firstName: 'Hameed',
  lastName: 'Basha',
  userKey: 'Key1'}]
Run Code Online (Sandbox Code Playgroud)

我需要使用任何javascript方法,如map等

gur*_*372 5

使用 map

var output = arr.map( s => ( s.userKey = "Key1", s ) );
Run Code Online (Sandbox Code Playgroud)

演示

var arr = [{
    gsm: 'gsm',
    firstName: 'firstname',
    lastName: 'lastname'
  },
  {
    gsm: '123456789',
    firstName: 'Mohamed',
    lastName: 'Sameer'
  },
  {
    gsm: '987654321',
    firstName: 'Hameed',
    lastName: 'Basha'
  }
];

var output = arr.map( s => ( s.userKey = "Key1", s ) );

console.log( output );
Run Code Online (Sandbox Code Playgroud)

  • 这将改变原始数组`arr`. (3认同)
  • 我认为forEach在这种情况下更合适`arr.forEach(s => s.userKey ="Key1");`.由于数组中的值都没有更新,因此只有它们引用的对象. (2认同)