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

时间:2018-01-11 07:08:59

标签: javascript arrays json object

这是我的json:

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

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

[ { gsm: 'gsm',
  firstName: 'firstname',
  lastName: 'lastname',
  userKey: 'Key1'},
{ gsm: '123456789',
  firstName: 'Mohamed',
  lastName: 'Sameer',
  userKey: 'Key1'},
{ gsm: '987654321',
  firstName: 'Hameed',
  lastName: 'Basha',
  userKey: 'Key1'}]

我需要使用任何javascript方法来完成此操作,例如map ... etc

5 个答案:

答案 0 :(得分:5)

使用map

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

<强>演示

&#13;
&#13;
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 );
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用Object.assign生成对象的副本并分配新属性并使用Array#map获取新数组。

var original = [ { gsm: 'gsm', firstName: 'firstname', lastName: 'lastname' }, { gsm: '123456789', firstName: 'Mohamed', lastName: 'Sameer' }, { gsm: '987654321', firstName: 'Hameed', lastName: 'Basha' }],
    copy = original.map(o => Object.assign({}, o, { key: 'key1' }));
    
console.log(copy);
console.log(original);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

如果您不想改变原始数组:

&#13;
&#13;
const arr = [ { gsm: 'gsm',
  firstName: 'firstname',
  lastName: 'lastname' },
{ gsm: '123456789',
  firstName: 'Mohamed',
  lastName: 'Sameer'},
{ gsm: '987654321',
  firstName: 'Hameed',
  lastName: 'Basha'}]
  
 const newArr = arr.map(item => ({
   ...item,
   userKey: 'Key1',
 }))
 
 console.log(newArr)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

data.map(el => Object.assign(el, {userKey: 'Key1'}))

data.map(el => ({ ...el, userKey: 'Key1' }))

答案 4 :(得分:0)

你可以这样做:)

this.props