Primoz Rome Primoz Rome - 2 months ago 9
Javascript Question

javascript 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 opertions and so on but I am sure there's a better way..

Answer

You can use Array#map method along with Array#join method. Where Array#filter method can be used for filtering non-empty and defined property values.

function obsKeysToString(o, k, sep) {
 // iterate over key array
 return k.map(function(key) {
    // get object property value 
    return o[key];
    // filter out non-empty and defined property
  }).filter(function(v) {
    return v;
    // join the property value array with the separator
  }).join(sep);
}

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

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

function obsKeysToString(o, k, sep) {
  return k.map(function(key) {
    return o[key];
  }).filter(function(v) {
    return v;
  }).join(sep);
}

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


Same solution with ES6 arrow function

function obsKeysToString(o, k, sep) {
 return k.map(key => o[key]).filter(v => v).join(sep);
}

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

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

function obsKeysToString(o, k, sep) {
  return k.map(key => o[key]).filter(v => v).join(sep);
}
console.log(obsKeysToString(obj, keys, '-'))


Another solution using Array#reduce method.

function obsKeysToString(o, k, sep) {
  // iterate over key array
  return k.reduce(function(str, key) {
    // generate string based on each key
    return str + (o.hasOwnProperty(key) ? (str.length ? sep : '') + o[key] : '');
  }, '')
}

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

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

function obsKeysToString(o, k, sep) {
  return k.reduce(function(str, key) {
    return str + (o.hasOwnProperty(key) ? (str.length ? sep : '') + o[key] : '');
  }, '')
}

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