0

I have something like that :

a = [{"country":"Colombia","date":"1995"}, {"country":"China","date":"1995"},{"country":"USA","date":"1992"}]

And what I want is that : "Colombia-China-USA"

I thought to use join('-') but a is not like that : a = ['Colombia', 'China', 'USA']

Could you help me please ?

Thank you very much !

Peter
  • 13
  • 4
  • 2
    use map to get the array of countries and then join `a.map(({country}) => country).join('-')` – cmgchess Jan 22 '23 at 12:45
  • 1
    https://stackoverflow.com/a/47277437/13583510 – cmgchess Jan 22 '23 at 12:53
  • @cmgchess: just out of curiosity, how `a.map(({country}) => country)` is better than `a.map(x => x.country)`? – gog Jan 22 '23 at 12:56
  • @gog it's not 'better' in this case, just preference. (there are cases where destructuring provides actual functionality within the callback, ie filtering out keys) – pilchard Jan 22 '23 at 13:02
  • @gog it is semantically the same, cmgchess' version does the unpacking in the parameter – YAMM Jan 22 '23 at 13:02
  • Does this answer your question? [Perform .join on value in array of objects](https://stackoverflow.com/questions/16607557/perform-join-on-value-in-array-of-objects) – pilchard Jan 22 '23 at 13:03
  • @gog in this case yours is actually shorter – cmgchess Jan 22 '23 at 13:09

3 Answers3

1

Firstly you can get country names as an array using map.

const coutries = a.map((item) => item.country)

Now the output array will be like this.

['Colombia', 'China', 'USA']

then you can join that array using join method.

const coutries = a.map(item => item.country).join('-');
0

You can use simple JavaScript:

let a = [{"country":"Colombia","date":"1995"}, {"country":"China","date":"1995"},{"country":"USA","date":"1992"}];
let b = "";
for (let i = 0; i < a.length; i++) {
    b+=a[i]["country"];
    if(i!=a.length-1) b+="-";
}
console.log("b = "+b);
0

You can use also reduce method like this:

const listCountries = a.reduce((list, curr, index) =>{ 
    if( index === 0) { list = list+ curr.country;} else{ list = list +"-"+curr.country;};
return list;
},"");

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

FaFa
  • 358
  • 2
  • 16