【问题标题】:concatenate two objects containing arrays in to one array containing objects将两个包含数组的对象连接到一个包含对象的数组中
【发布时间】:2017-10-31 20:37:30
【问题描述】:

我正在尝试将两个包含对象的数组连接成一个包含所有对象的数组,我希望它有意义

 getEntries() {
        const linksArr = ['/api/aggregated', '/api/techmetro'];

        axios.all(linksArr.map(l => axios.get(l))).then(axios.spread((...res) => {
            // all requests are now complete
            this.articles = res;
        }));
    },

我明白了

articles:Array[2]
0:Object
config:Object
data:Object
data:Array[10]
    0: Object
    ...
meta:Object
headers:Object
request:XMLHttpRequest
status:200
statusText:"OK"
1:Object
config:Object
data:Object
    data:Array[1]
    0: Object
0:Object
meta:Object
headers:Object
request:XMLHttpRequest
status:200
statusText:"OK"

但我想要的是:

articles:Array[11]
   0: Object
    ...

我错过了什么?非常感谢

【问题讨论】:

  • 好吧,您将请求作为数组发送,以便它们得到正确解析,但是,响应包含一个具有名为 data 的属性的对象,我猜这是您希望连接的对象,不是响应本身
  • 是的,但是 axios.spread((...res.data) 和 this.articles = res.data 都可以工作
  • "axios.spread((...res)" 看起来真的不对

标签: javascript arrays object ecmascript-6


【解决方案1】:

我认为最简单的方法是从响应中获取数据,例如

... .then( allresponses => 
   allresponses.reduce( (current, item) => current.concat( item.data ), []) ...

【讨论】:

    【解决方案2】:

    我想你正在寻找

    ….then(([aggregateds, techmetros]) => {
        this.articles = aggreateds.concat(techmetros);
    });
    

    或同等的

    ….then(res => {
        this.articles = res[0].concat(res[1]);
    });
    

    如果可以连接多个数组(即res.length != 2),您可以使用[].concat(...res)

    【讨论】:

    • 这仍然只会连接响应,而不是 data 属性下的文章
    • 非常感谢 Bergi 和 icepickle,concat 总是抛出 .concat is not a function ..如果我尝试访问 .data ` .then(res => { this.articles = res[0].data。 concat(res[1].data); });`
    • @Icepickle 啊,我无法解读非 JSON 表示,我只是接受了“两个包含对象的数组”的描述。当然添加该属性访问器是微不足道的,或者在解构中使用([{data: aggregateds}, {data: techmetros}]) => …
    猜你喜欢
    • 1970-01-01
    • 2011-10-28
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多