所以,让我们假设我有这个:
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
如果我这样做:var officersIds = officers.map(x => [x.name, x.lastName]);
officersIds
的结果将是这样:
[ "Captain", "Piett" ], [ "General", "Veers" ], [ "Admiral", "Ozzel" ], [ "Commander", "Jerjerrod" ]
对吗?
所以,我需要做的是在每次地图迭代中放置一个对象,因此现在的输出是这样,例如:
[["x", "y"], [ "Captain", "Piett" ]],
[["x", "y"], [ "General", "Veers" ]],
[["x", "y"], [ "Admiral", "Ozzel" ]],
[["x", "y"], [ "Commander", "Jerjerrod" ]]
我为什么需要这个?最好不要问;)但这是一个复杂的问题,如果您能帮助我解决这个简单的问题,我可以将您的解决方案转移到我的复杂问题上。
重要提示:有没有办法在一行中做到这一点?
在特定索引处使用拼接。
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
var officersIds = officers.map(x => [x.name, x.lastName]);
officersIds.splice(0, 0, ['x','y']);
// or officersIds.unshift(['x','y'])
console.log(officersIds);
您可以使用spread operator将其设置为单线:
var officersIds = [['x', 'y'], ...officers.map(x => [x.name, x.lastName])];
请参见下面的概念证明:
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
var officersIds = [['x', 'y'], ...officers.map(x => [x.name, x.lastName])];
console.log(officersIds);
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' },
];
officers.unshift({ name: x, lastName: y });
var officersIds = officers.map(x => [x.name, x.lastName]);
或
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' },
];
var officersIds = officers.map(x => [x.name, x.lastName]);
officersIds.unshift(["x", "y" ]);