Peter
Peter

Reputation: 43

How can I do to join value of array of dicts?

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 !

Upvotes: 0

Views: 45

Answers (3)

FaFa
FaFa

Reputation: 398

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

Upvotes: 0

Maxim Diamandi
Maxim Diamandi

Reputation: 1

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

Upvotes: 0

Isuru Madusanka
Isuru Madusanka

Reputation: 80

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

Upvotes: 1

Related Questions