简体   繁体   English

在JavaScript中使用数组映射对象

[英]Map object with array in javascript

I'm using Vue Select Image for multi selecting images. 我正在使用Vue Select Image进行多重选择图像。 Vue Select Image expects the array to be with the following keys Vue Select Image期望数组具有以下键

 [{ id: '1', src: 'https://unsplash.it/200?random', alt: 'Alt Image 1' }, { id: '2', src: 'https://unsplash.it/200?random', alt: 'Alt Image 2' }] 

And my api route gives the object with following keys: 而且我的api路由为对象提供了以下键:

 (2)[{…}, {…}] 0: created_at: "2019-07-26 07:44:56" id: 3 name: null path: "img/d1ef5a9c54ee32df12c213b1491e1636.jpg" thumb: "img/thumb_d1ef5a9c54ee32df12c213b1491e1636.jpg" updated_at: "2019-07-26 07:44:56" 

Below is my code snippet: 以下是我的代码段:

 import VueSelectImage from "vue-select-image"; import "vue-select-image/dist/vue-select-image.css"; export default { data() { return { dataImages: [{ id: "", src: "", alt: "" }] }, selected: {}, initialLoad() { axios.get("api/gallery").then(response => { this.dataImages = Object.keys(response.data.data).map(function(key) { return [Number(key), response.data.data[key]]; }); // console.log(response.data.data); }); }, components: { VueSelectImage }, }; 
 <template> <div> <vue-select-image :dataImages="dataImages" @onselectimage="selected"></vue-select-image> </div> </template> 

The above code maps object with array with its own keys. 上面的代码使用带有自己的键的数组映射对象。 And displays 2 circle as there are 2 data receiving from api. 并显示2个圆圈,因为有2个数据从api接收。 Clicking on them gives the following error: 单击它们会出现以下错误:

Error in event handler for "onselectimage": "TypeError: fns.apply is not a function" “ onselectimage”事件处理程序中的错误:“ TypeError:fns.apply不是函数”

Map through array of objects you get from API, it returns new array with objects with desired fields. 映射通过API获得的对象数组,它返回带有所需字段的对象的新数组。

axios.get("api/gallery").then(response => {
  this.dataImages = response.data.data.map((obj, index) => {
    return {
      id: obj.id,
      src: obj.path,
      alt: `Alt image ${index}`
    };
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM