4 回答
TA贡献2012条经验 获得超12个赞
map
像这样使用:
const arr = data.map(city => city.name + ", " + city.country);
arr
data
将是一个与 in中的每个city
对象data
映射到 string 的长度相同的新数组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);
TA贡献1788条经验 获得超4个赞
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(i => `${i.name} , ${i.country}`);
console.log(arr)
TA贡献1864条经验 获得超6个赞
forEach 的简单解决方案
countries = [
{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"}
]
let arr = [];
let result = [];
countries.forEach((country, index) => {
let nameStr = `${country.name}, ${country.country}`
result.push(nameStr);
})
console.log(result)
//output
//["les Escaldes Andorra", "Andorra la Vella Andorra", "Umm al Qaywayn United Arab Emirates", "Ras al-Khaimah United Arab Emirates"]
TA贡献1862条经验 获得超6个赞
如果您愿意,可以使用reduce函数:
arr.reduce((acc, curr) => [...acc, (`${curr.name}, ${curr.country}`)], []);
它将以您想要的格式返回您的值。
下面的例子。
const arr = [
{country: 'Andorra', geonameid: 3040051, name: 'les 1', subcountry: 'Escaldes-Engordany'},
{country: 'Turkey', geonameid: 3040021, name: 'les Escaldes', subcountry: 'aaaa'},
{country: 'IDK', geonameid: 3040021, name: 'Wow', subcountry: 'aaaa'}
];
const custom = arr.reduce((acc, curr) => [...acc, (`${curr.name}, ${curr.country}`)], []);
console.log(custom);
添加回答
举报