Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine object key values into single string with separator

Tags:

javascript

I want to achieve this:

var keys = ['name', 'description']

var obj = {
  id: 1,
  name: 'Test',
  description: 'Lorem ipsum dolores',
  moreKeysHere: 'moreValues'
}

console.log(obsKeysToString(obj, keys, '-'))

Result: Test - Lorem ipsum dolores

I have some solution with for loop, and some stirring operations and so on but I am sure there's a better way..

like image 659
Primoz Rome Avatar asked Sep 14 '16 18:09

Primoz Rome


1 Answers

Another answer to show 1-liners for joining keys, or values, or both:


Join Keys: Object.keys(obj)

const 
  obj    = {a: '1', b: '2'},
  joined = Object.keys(obj).join(',');

Join Values: Object.values(obj)

const 
  obj    = {a: '1', b: '2'},
  joined = Object.values(obj).join(',');

Join Both: Object.entries(obj)

const 
  obj    = {a: '1', b: '2'},
  joined = Object.entries(obj).join(',');

Note: Object.entries(obj) was announced a standard by ecma in June 2017 (See link). Browser support: all except IE Desktop and Mobile Safari.

enter image description here

Update: Object.entries(obj) now supports in Mobile Safari Also

Ref: developer.mozilla.org

enter image description here

like image 183
Adam Moisa Avatar answered Oct 09 '22 22:10

Adam Moisa