一般我们合并对象使用Object.assign(json1,json2)
例子:
<script>
let json={
type:"Fruits",
stock:"100"
};
let array = [{
name: "桃子",
E_name: "Peach",
size: "20",
color: "red"
}, {
name: "苹果",
size: "apple",
color: "red"
}, {
name: "橘子",
E_name: "Orange",
color: "Orange"
}];
let newArray=[]
for (let index = 0; index < array.length; index++) {
const element = array[index];
let a=Object.assign(json,element)
console.log(a)
newArray.push(a)
}
console.log(newArray)
</script>
以为结果是这样的:
标题可惜事与愿违,结果是这样的:
标题为什么不行,因为Object.assign()数组合并是浅拷贝,
let newArray = []
for (let index = 0; index < array.length; index++) {
const element = array[index];
for (let val in json) {
element[val] = json[val]
}
console.log("循环输出:")
console.log(element)
newArray.push(element)
}
console.log("最后的结果:")
console.log(newArray)