1

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

3 Answers 3

4

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}

Sign up to request clarification or add additional context in comments.

3 Comments

you need to use .join(',') to join the strings with a comma.
The default is ,, so I don't have to add the comma
@IvanParedes - you're welcome! The first works to, but it's not supported in most browsers yet, but it will be.
1

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(",") );

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.