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
Son le
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);
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);
+7
Alexander T.
source
to share
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));
+1
KJ Price
source
to share
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);
+1
Lewis
source
to share
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
Kailash yadav
source
to share
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
Ralf Zimmermann
source
to share