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 妈妈生日祝福语简短励志