Can we convert JSON Array of Objects to lightGalery Array of Objects?

佐手、 提交于 2019-12-11 06:08:54

问题


Hello all senior web developers, I am newbie for web development. I have used lightGallery plugin to view images. But my image path stored in array. In array element always dynamic that get from ajax response. This is My array :

     var data = { "result" : [ 
                                { "file_name"  : "a.jpg" },
                                { "file_name"  : "b.png"},
                                  ......................
                             ]
     }       

// This is Lightgallery array syntax

     $(this).lightGallery({
       dynamic: true,
       dynamicEl: [{"src": 'your image path'}, 
                   {'src': 'your image path'},
                    ........................
                  ]
     })

// I want like this :

     $(this).lightGallery({
       dynamic: true,
       dynamicEl: [{"src": 'a.jpg'}, 
                   {'src': 'b.jpg'},
                   ................
                  ]
     })

How to do that? Can or not?

thank for valuable help.


回答1:


Array.prototype.map() is convenient for creating new arrays based on originals.

See below for a practical example.

// Input.
const input = {
  result: [ 
    { "file_name"  : "a.jpg" },
    { "file_name"  : "b.png"}
  ]
}

// To Dynamic.
const toDynamic = ({result}) => ({
  dynamic: true,
  dynamicEl: result.map(x => ({src: x.file_name}))
})

// Output.
const output = toDynamic(input)

// Proof.
console.log(output)



回答2:


Your original var data is actually an object - see how it starts with a {.

const data = { "result" : [ 
  { "file_name"  : "a.jpg" },
  { "file_name"  : "b.png"},
]};
const dynamicElArr = data.result.map(({ file_name: src }) => ({ src }));
console.log(dynamicElArr);

Then you can use it for dynamicEl.



来源:https://stackoverflow.com/questions/49441079/can-we-convert-json-array-of-objects-to-lightgalery-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!