gpt4 book ai didi

javascript - 从 JSON 文件中获取一组特定的键/值对

转载 作者:行者123 更新时间:2023-12-03 23:59:05 25 4
gpt4 key购买 nike

初学者 - 我想从 JSON 文件为我的世界城市类型提前项目创建一个数组。我已经获取了数据,现在我想提取 2 个键/值对(称为名称/国家/地区)并将它们推送到一个具有以下语法的新字符串数组中:

const arr = ["name, country", "name, country", "name, country"...]
以下是数据示例:
[]:
0: {country: "Andorra", geonameid: 3040051, name: "les Escaldes", subcountry: "Escaldes-Engordany"}
1: {country: "Andorra", geonameid: 3041563, name: "Andorra la Vella", subcountry: "Andorra la Vella"}
2: {country: "United Arab Emirates", geonameid: 290594, name: "Umm al Qaywayn", subcountry: "Umm al Qaywayn"}
3: {country: "United Arab Emirates", geonameid: 291074, name: "Ras al-Khaimah", subcountry: "Raʼs al Khaymah"}...
我知道我必须使用 .push().forEach()或 for 循环,但我不知道如何去做。谁能告诉我怎么做?

最佳答案

使用 map 像这样:

const arr = data.map(city => city.name + ", " + city.country);
arr将是一个与 data 长度相同的新数组凡 city对象在 data映射到字符串 city.name + ", " + city.country .
演示:

const data = [ {country: "Andorra", geonameid: 3040051, name: "les Escaldes", subcountry: "Escaldes-Engordany"}, {country: "Andorra", geonameid: 3041563, name: "Andorra la Vella", subcountry: "Andorra la Vella"}, {country: "United Arab Emirates", geonameid: 290594, name: "Umm al Qaywayn", subcountry: "Umm al Qaywayn"}, {country: "United Arab Emirates", geonameid: 291074, name: "Ras al-Khaimah", subcountry: "Raʼs al Khaymah"} ];

const arr = data.map(city => city.name + ", " + city.country);

console.log(arr);

关于javascript - 从 JSON 文件中获取一组特定的键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65075777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com