JavaScript 使用映射重新格式化数组中的对象
示例
Array.prototype.map():返回一个新数组,并在原始数组中的每个元素上调用提供的函数。
以下代码示例获取人员数组,并创建一个新数组,其中包含具有“fullName”属性的人员
var personsArray = [
{
id: 1,
firstName: "Malcom",
lastName: "Reynolds"
}, {
id: 2,
firstName: "Kaylee",
lastName: "Frye"
}, {
id: 3,
firstName: "Jayne",
lastName: "Cobb"
}
];
//返回由全名组成的新对象数组。
var reformatPersons = function(persons) {
return persons.map(function(person) {
//创建一个新对象来存储全名。
var newObj = {};
newObj["fullName"] =person.firstName+ " " + person.lastName;
//返回我们的新对象。
return newObj;
});
};现在reformatPersons(personsArray),我们可以呼叫并收到一个仅包含每个人全名的新数组。
var fullNameArray = reformatPersons(personsArray);
console.log(fullNameArray);
///输出
[
{ fullName: "Malcom Reynolds" },
{ fullName: "Kaylee Frye" },
{ fullName: "Jayne Cobb" }
]personsArray其内容保持不变。
console.log(personsArray);
///输出
[
{
firstName: "Malcom",
id: 1,
lastName: "Reynolds"
}, {
firstName: "Kaylee",
id: 2,
lastName: "Frye"
}, {
firstName: "Jayne",
id: 3,
lastName: "Cobb"
}
]
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短