-
繁花如伊
map像这样使用:const arr = data.map(city => city.name + ", " + city.country);arrdata将是一个与 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);
-
尚方宝剑之说
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)
-
慕尼黑的夜晚无繁华
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"]
-
阿波罗的战车
如果您愿意,可以使用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);