Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Combine array values into one single value

I have this object

a = {key:'animals',
     options: ['dog','cat','penguin']}

How can I simplify it to this:

b = ['animals','dogcatpenguin']
like image 511
Son Le Avatar asked Dec 05 '22 22:12

Son Le


2 Answers

Like so

var a = {
  key: 'animals',
  options: ['dog','cat','penguin']
};

var key, b = [];

for (key in a) {
  b.push(Array.isArray(a[key]) ? a[key].join('') : a[key]);
}

console.log(b);

Or you can use Object.keys with .map

var a = {
    key: 'animals',
    options: ['dog','cat','penguin']
};

var b = Object.keys(a).map(function (key) {
    return Array.isArray(a[key]) ? a[key].join('') : a[key];     
});

console.log(b);
like image 93
Oleksandr T. Avatar answered Dec 08 '22 12:12

Oleksandr T.


Try this

var a = {
  key: 'animals',
  options: ['dog', 'cat', 'penguin']
}
var result = Object.keys(a).map(function(key){
  var item = a[key];
  return item instanceof Array ? item.join('') : item;
});
console.log(result);
like image 40
Lewis Avatar answered Dec 08 '22 11:12

Lewis