Get values and join with ','
const users = [{
name: "Jon",
age: 34,
country: "ES"
}]
users.map(function(a){
for (let item in a) {
console.log(a[item])
}
})
//users.join(", ");
I want to return Jon,34,ES
.
Any suggestions?
Get values and join with ','
const users = [{
name: "Jon",
age: 34,
country: "ES"
}]
users.map(function(a){
for (let item in a) {
console.log(a[item])
}
})
//users.join(", ");
I want to return Jon,34,ES
.
Any suggestions?
5 Answers
Reset to default 6You can use Object.values and map: Objet.values returns an array of values in the object and join converts these values to string by joining them by ',' here.
const users = [{
name: "Jon",
age: 34,
country: "ES"
}];
var result = users.map(u => Object.values(u).join(','));
console.log(result);
You can use Object.values to get an array of the properties of your object, then use the join method of that array to create a string from the values:
var result = users.map(function (a) {
return Object.values(a).join(', ');
});
console.log(result[0]); // Jon, 34, ES
You can map your users array and join the values of each user dictionary.
users.map(user => Object.values(user).join(', '));
const users = [{
name: "Jon",
age: 34,
country: "ES"
},{
name: "Sam",
age: 24,
country: "US"
}]
let arrayOfStrings = users.map(function(a){
return Object.values(a).join(',')
}
})
// arrayOfStrings = ["Jon,34,ES", "Sam,24,US"]
//ES6 way:
let arrayOfStrings = users.map( a => Object.values(a).join(',') )
// arrayOfStrings = ["Jon,34,ES", "Sam,24,US"]
arrayOfStrings will contains an array of strings made from objects.
For reference of the methods used:
Object.values
Array.prototype.join
Because there are already a bunch of solutions which work, I want to provide a different one.
Like your one:
const users = [{
name: "Jon",
age: 34,
country: "ES"
}]
const results = users.map(function(a) {
const values = [];
for (let item in a) {
values.push(a[item]);
}
return values.join(", ");
})
console.log(results);
Or for really old browser support (IE6+), like this:
var users = [{
name: "Jon",
age: 34,
country: "ES"
}]
var results = [];
for (var i = 0; i < users.length; i++) {
var values = [];
for (let x in users[i]) {
values.push(users[i][x]);
}
results.push(values.join(", "));
}
console.log(results);
Anyway, I'd prefer a modern solution using Arrow functions, Array.prototype.map and Object.values like others in this thread used.