这是我的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
答案 0 :(得分:5)
使用map
var output = arr.map( s => ( s.userKey = "Key1", s ) );
<强>演示强>
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;
答案 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)
如果您不想改变原始数组:
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;
答案 3 :(得分:0)
data.map(el => Object.assign(el, {userKey: 'Key1'}))
或
data.map(el => ({ ...el, userKey: 'Key1' }))
答案 4 :(得分:0)
你可以这样做:)
this.props