最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to join values of one object? - Stack Overflow

programmeradmin6浏览0评论

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?

Share Improve this question edited Nov 2, 2017 at 7:55 Werner 2,1643 gold badges24 silver badges34 bronze badges asked Nov 2, 2017 at 7:22 AlexAlex 6258 silver badges28 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

You 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:

  1. Object.values

  2. 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.

发布评论

评论列表(0)

  1. 暂无评论