我有两个从axios.get获取的对象和一个从rss feed获取的对象,结果是这样的: Two Object
对象的字段名称不同,但含义相同。例如:Title和Full_name是对象的名称。
当前我具有以下配置:
Obj1 = {title: "Main text 1", body: "text text 1"},
{title: "Main text 2", body: "text text 2"};
Obj2 = {full_name: "Main Text 3", description: "text text 3"};
我想要一个这样的对象:
Obj3= {name: "Main text 1", desc: "text text 1"},
{name: "Main text 2", desc: "text text 2"};
{name: "Main Text 3", desc: "text text 3"};
当前我正在使用以下代码:
<script>
export default {
data() {
return {
obj1: {},
obj2: {}
}
},
mounted() {
this.axios
.get('https://url.com')
.then((response) => {
this.obj1 = response.data;
});
fetch('https://url2.com')
.then((res) => res.json())
.then((response) => {
this.obj2 = response.items;
});
}
}
</script>
我尝试了以下解决方案,结果始终为空:
let merged = {...this.obj1, ...this.obj2};
var merged = Object.assign( {}, this.obj1, this.obj2);
答案 0 :(得分:0)
创建一个新的阵列名称为
var newArray[]
var Obj1 = {title: "Main text 1", body: "text text 1"},
{title: "Main text 2", body: "text text 2"};
var Obj2 = {full_name: "Main Text 3", description: "text text 3"};`enter newArray.Push(Obj1);
newArray.Push(Obj2);
答案 1 :(得分:0)
您应该map
进行第二个响应,然后concat
进行第一个响应。
var concObject = obj1.concat( obj2.map( item => ({name: item.full_name, desc: item.description}) ) )
注意:在您的示例中,obj1
和obj2
是数组。
答案 2 :(得分:0)
根据您的屏幕截图,this.obj1
和this.obj2
是 Arrays
因此,您可以通过使用方括号创建一个新数组,将它们与散布运算符合并:
let merged = [...this.obj1, ...this.obj2]
答案 3 :(得分:0)
问题是您的代码var merged = Object.assign( {}, this.obj1, this.obj2);
正在执行,然后通过API响应更新obj1 or obj2
。
您可以watch obj1
和obj2
。更改merged
或obj1
中的任何一个时,更新obj2
对象。
<template>
<div>Merged Object: {{ merged }}</div>
</template>
<script>
export default {
data() {
return {
obj1: {},
obj2: {},
merged: {}
}
},
mounted() {
this.axios
.get('https://url.com')
.then((response) => {
this.obj1 = response.data;
});
fetch('https://url2.com')
.then((res) => res.json())
.then((response) => {
this.obj2 = response.items;
});
},
watch: {
// whenever obj1 changes, this function will run
obj1(newVal, oldVal) {
this.merged = Object.assign( {}, newVal, this.obj2);
},
// whenever obj2 changes, this function will run
obj2(newVal, oldVal) {
this.merged = Object.assign( {}, newVal, this.obj1);
}
}
}
</script>