zoukankan      html  css  js  c++  java
  • 数组映射到对象

    <!DOCTYPE html>
    <head>
    	<meta charset="utf-8"/>
    </head>
    <p>
    	你有一个 user 对象数组,每个对象都有 name,surname 和 id。
    	
    	编写代码以该数组为基础,创建另一个具有 id 和 fullName 的对象数组,其中 fullName 由 name 和 surname 生成。
    	
    	例如:
    	
    	let john = { name: "John", surname: "Smith", id: 1 };
    	let pete = { name: "Pete", surname: "Hunt", id: 2 };
    	let mary = { name: "Mary", surname: "Key", id: 3 };
    	
    	let users = [ john, pete, mary ];
    	
    	let usersMapped = /* ... your code ... */
    	
    	/*
    	usersMapped = [
    	  { fullName: "John Smith", id: 1 },
    	  { fullName: "Pete Hunt", id: 2 },
    	  { fullName: "Mary Key", id: 3 }
    	]
    	*/
    	
    	alert( usersMapped[0].id ) // 1
    	alert( usersMapped[0].fullName ) // John Smith
    	所以,实际上你需要将一个对象数组映射到另一个对象数组。在这儿尝试使用箭头函数 => 来编写。
    </p>
    
    <script type="text/javascript">
    	'use strict';
    	
    	let john = { name: "John", surname: "Smith", id: 1 };
    	let pete = { name: "Pete", surname: "Hunt", id: 2 };
    	let mary = { name: "Mary", surname: "Key", id: 3 };
    	
    	let users = [ john, pete, mary ];
    	
    	let usersMapped = users.map( user => (
    	{
    		fullName : `${user.name} ${user.surname}`,
    		id : user.id
    	}))
    	
    	/*
    	usersMapped = [
    	  { fullName: "John Smith", id: 1 },
    	  { fullName: "Pete Hunt", id: 2 },
    	  { fullName: "Mary Key", id: 3 }
    	]
    	*/
    	
    	alert( usersMapped[0].id) // 1
    	alert( usersMapped[0].fullName ) // John Smith
    	
    	
    </script>
    
    <p>
    	请注意,在箭头函数中,我们需要使用额外的括号。
    	
    	我们不能这样写:
    	
    	let usersMapped = users.map(user => {
    	  fullName: `${user.name} ${user.surname}`,
    	  id: user.id
    	});
    	我们记得,有两种箭头函数的写法:直接返回值 value => expr 和带主体的 value => {...}。
    	
    	JavaScript 在这里会把 { 视为函数体的开始,而不是对象的开始解决方法是将它们包装在普通括号 () 中:
    	
    	let usersMapped = users.map(user => ({
    	  fullName: `${user.name} ${user.surname}`,
    	  id: user.id
    	}));
    	这样就可以了。
    </p>
    

      

  • 相关阅读:
    linux日常管理-rsync后台服务方式-1
    linux日常管理-rsync_ssh方式
    linux日常管理-rsync常用选项详解
    linux日常管理-rsync格式
    socket 服务端 | socket 客户端 -->黏包现象
    udp 服务端 | udp 客户端 --循环发消息
    udp 协议 服务端 | udp 客户端
    socket tcp 服务端 | socket tcp 客户端 -->之循环
    socket tcp 服务器 | socket tcp 客户端
    计算器写法 | '1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
  • 原文地址:https://www.cnblogs.com/perfectdata/p/15496709.html
Copyright © 2011-2022 走看看