Ivan Paredes
Ivan Paredes

Reputation: 475

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";

Upvotes: 1

Views: 227

Answers (3)

adeneo
adeneo

Reputation: 318182

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}

Upvotes: 4

Steeve Pitis
Steeve Pitis

Reputation: 4443

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

var keys = Object.keys(obj);
var str1 = keys.join(',');
var str2 = keys.map(function(key){ return obj[key] }).join(',');

console.log(str1)
console.log(str2)

Look this one ;)

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Try this as well

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

console.log( "String 1", Object.keys( obj ).join(",") );

console.log( "String 2", Object.keys( obj ).map( function( key ){ return obj[ key ] } ).join(",") );

Upvotes: 1

Related Questions