'Combine object key values into single string with separator

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



Solution 1:[1]

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

Solution 2:[2]

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

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

// ES6 
console.log(keys.filter(key => typeof obj[key] !== 'undefined').map(key => obj[key]).join(','));

// NON ES6 
console.log(keys.filter(function(key) { return typeof obj[key] !== 'undefined'}).map(function(key) { return obj[key]}).join(','));

Solution 3:[3]

Another solution with one line of code...

var stringRep = Object.keys(obj).toString();

//stringRep = "id,name,description,moreKeysHere"

Solution 4:[4]

Using Array.reduce :

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

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

console.log (
  keys.reduce (
    function (strs, key) { if (obj[key]) strs.push (obj[key]);
                           return strs }, []).join (' - ')
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aryan
Solution 2
Solution 3 KpTheConstructor
Solution 4 HBP