Ivan Paredes Ivan Paredes - 2 months ago 7
Javascript Question

how to split object in 2 strings. keys in one string, values in other string

how can split object in 2 strings?.
keys in one string,
values in other string

my object is this.

var obj = {
mail: 'mailObjeto',
nombre: 'nombreObjeto',
apellido: 'apellidoObjeto'
};


deseable output

string 1: "mail,nombre,apellido";
string 2:"mailObjeto,nombreObjeto,apellidoObjeto";

Answer

In the latest Chrome(51 still behind a flag though) and Firefox(47) you can do

var obj = {
  mail: 'mailObjeto',
  nombre: 'nombreObjeto',
  apellido: 'apellidoObjeto'
};

var string1 = Object.keys(obj).join();
var string2 = Object.values(obj).join();

console.log(string1);
console.log(string2);
.as-console-wrapper {top:0}

As support for Object.values is still somewhat lacking, here's another way

var obj = {
  mail: 'mailObjeto',
  nombre: 'nombreObjeto',
  apellido: 'apellidoObjeto'
};

var string1 = Object.keys(obj);
var string2 = string1.map(function(k) { return obj[k] });

string1 = string1.join();
string2 = string2.join();

console.log(string1);
console.log(string2);
.as-console-wrapper {top:0}