1、合并
<script>
var arr = [
{name:"lisi",
age:18,
likes:["lol","足球"],
alikes:["音乐","电影"],
sex:"male"
},
{name:"ss",
age:11,
likes:["lol","足g球"],
alikes:["音e乐","电影"],
sex:"mafle"
},
{name:"ll",
age:90,
likes:["losl","足s球"],
alikes:["音q乐","电n影"],
sex:"madle"
}
]
var res = [];
for(var i = 0 ; i<arr.length ; i++){
console.log(arr[i]);
var name = arr[i].name;
var age = arr[i].age;
var likes = arr[i].likes.concat(arr[i].alikes);
res.push(
{
name:name,
age:age,
likes:likes
}
)
}
console.log(res);
</script>
2、合并es6
<script>
var arr = [
{
name: "lisi",
age: 18,
likes: ["lol", "足球"],
alikes: ["音乐", "电影"],
sex: "male"
},
{
name: "ss",
age: 11,
likes: ["lol", "足g球"],
alikes: ["音e乐", "电影"],
sex: "mafle"
},
{
name: "ll",
age: 90,
likes: ["losl", "足s球"],
alikes: ["音q乐", "电n影"],
sex: "madle"
}
]
var res = [];
for(var i = 0; i<arr.length; i++){
// 解构
var {name,age,likes,alikes} = arr[i];
// 展开
likes.push(...alikes);
// 键和值相同只用写一个
var obj ={
name,
age,
likes
}
res.push(obj);
}
console.log(res)
</script>
3、字符串模板
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<script>
var arr = [
{ imgUrl:"https://img2.baidu.com/it/u=224367962,4034417299&fm=26&fmt=auto",
name:"cheng",age:19},
{ imgUrl:"https://img1.baidu.com/it/u=2848172350,1423562335&fm=26&fmt=auto",
name:"lisi",age:18}
]
for(var i = 0;i<arr.length;i++){
var {imgUrl,name,age} = arr[i];
var template = `
<div>
<p>${name}</p>
<img src = "${imgUrl}"/>
<p>${age}</p>
</div>
`
console.log(template);
$("body").prepend(template)
}
</script>