JS Concatenate array values ​​into one value

I have this object

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

      

How can I simplify this:

b = ['animals','dogcatpenguin']

      

+3


source to share


5 answers


So here

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

Run code


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

Run code


+7


source


You can just create a new array with the calculated values



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

var b = [
  a.key,
  a.options.join('')
];

document.write(JSON.stringify(b));
      

Run code


+1


source


try it

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

Run code


+1


source


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

var idx, b = [];

for (idx in a) { //Iterate through all the items of object a
  b.push(Array.isArray(a[key]) ? a[key].join('') : a[key]); //Check if item is array join with (blank) or if not directly push it new array
}

console.log(b);

      

+1


source


Another possible solution.

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

var b = new Array();
for(var index in a) { 
    var attr = a[index].toString().split(",").join("");
    b.push(attr);
}

      

+1


source







All Articles