按字母顺序排列数组的第一个元素,如 - arr[name][image]?
Sorting alphabetically the first elements of an array like - arr[name][image]?
我在 json 中有一个包含 100 张图像的数组,格式如下:
[{"name":"one","image":"one.jpeg"},
{"name":"two","image":"two.jpeg"},
{"name":"three","image":"three.jpeg"}]
我想以列表的形式打印所有“名称”元素,而不是图像。
我尝试在下面的代码中将 json 转换为字符串。我也想按字母顺序排序。
我想我需要一个循环?还是有更好的方法?
if (message.content === '!list') {
const list= commandArray[0];
const myJSON = JSON.stringify(list);
message.channel.send(myJSON);
}
我首先使用 JSON.parse()
将 JSON 转换为数组,然后使用自定义比较函数对图像进行排序,该函数仅按 name
字段按升序排序.然后我通过排序数组和 return 映射一个仅包含每个元素的 name
字段的新数组,然后打印它。
let images_json = '[{"name":"alpha","image":"alpha.jpeg"}, {"name":"delta","image":"delta.jpeg"},{"name":"charlie","image":"charlie.jpeg"}]';
let images = JSON.parse(images_json)
console.log(images); //printing to console before sort
images.sort(function(a, b) {
if (a.name > b.name) {
return 1;
}
if (b.name > a.name) {
return -1;
}
return 0;
});
console.log(images); //printing to console after sort
let images_names = images.map(img => img.name);
console.log(images_names) //printing only the names of the images
我在 json 中有一个包含 100 张图像的数组,格式如下:
[{"name":"one","image":"one.jpeg"},
{"name":"two","image":"two.jpeg"},
{"name":"three","image":"three.jpeg"}]
我想以列表的形式打印所有“名称”元素,而不是图像。
我尝试在下面的代码中将 json 转换为字符串。我也想按字母顺序排序。 我想我需要一个循环?还是有更好的方法?
if (message.content === '!list') {
const list= commandArray[0];
const myJSON = JSON.stringify(list);
message.channel.send(myJSON);
}
我首先使用 JSON.parse()
将 JSON 转换为数组,然后使用自定义比较函数对图像进行排序,该函数仅按 name
字段按升序排序.然后我通过排序数组和 return 映射一个仅包含每个元素的 name
字段的新数组,然后打印它。
let images_json = '[{"name":"alpha","image":"alpha.jpeg"}, {"name":"delta","image":"delta.jpeg"},{"name":"charlie","image":"charlie.jpeg"}]';
let images = JSON.parse(images_json)
console.log(images); //printing to console before sort
images.sort(function(a, b) {
if (a.name > b.name) {
return 1;
}
if (b.name > a.name) {
return -1;
}
return 0;
});
console.log(images); //printing to console after sort
let images_names = images.map(img => img.name);
console.log(images_names) //printing only the names of the images