我知道如何对对象数组进行操作,但是从来没有必要将数组数据填充到另一个数组中。我需要将名字+姓氏字段填充到出生数组的名字字段中
let birth = [
{name: '' }
]
首先我的数组为空,我想用这些数据填充它
let names = [
{firstname: "Julien", lastname: "DEHAIS"},
{firstname: "Cyril", lastname: "GUIGUIAN"},
{firstname: "Pascal", lastname: "BOUTRIN"},
{firstname: "Franck", lastname: "BORDERIE"},
{firstname: "Arnold", lastname: "GIRARD"}
]
得到这样的东西
let birth = [
{name: 'Julien DEHAIS' },
{name: 'Cyril GUIGUIAN' },
{name: 'Pascal BOUTRIN' },
{name: 'Franck BORDERIE' },
{name: 'Arnold GIRARD' }
]
请有人帮助我
答案 0 :(得分:1)
您可以使用map()
并返回具有name
属性的新对象
let names = [ {firstname: "Julien", lastname: "DEHAIS"}, {firstname: "Cyril", lastname: "GUIGUIAN"}, {firstname: "Pascal", lastname: "BOUTRIN"}, {firstname: "Franck", lastname: "BORDERIE"}, {firstname: "Arnold", lastname: "GIRARD"} ]
const res = names.map(x => ({name: `${x.firstname} ${x.lastname}`}))
console.log(res)
答案 1 :(得分:1)
简单的map
:
let names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
const res = names.map(({ firstname, lastname }) => ({ name: firstname + " " + lastname }));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5语法:
var names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
var res = names.map(function(e) {
return { name: e.firstname + " " + e.lastname };
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }