Home > database >  How can I do to join value of array of dicts?
How can I do to join value of array of dicts?

Time:01-23

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 !

CodePudding user response:

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('-');

CodePudding user response:

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);

CodePudding user response:

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

  • Related