问题
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