Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  129] [ 1]  / answers: 1 / hits: 158258  / 7 Years ago, tue, may 23, 2017, 12:00:00

I have written this small function to get all keys and values of an object and store them into an array. The object might contain arrays as values...



Object { 0: [1,2,3,4] } to [0,1,2,3,4] converting all elements to integers



I wonder whether there is a faster/cleaner way to do so:



function flattenObject(obj) {
// Returns array with all keys and values of an object
var array = [];
$.each(obj, function (key, value) {
array.push(key);
if ($.isArray(value)) {
$.each(value, function (index, element) {
array.push(element);
});
}
else {
array.push(value);
}
});

return array
}

More From » arrays

 Answers
6

You could just concat all keys and values. (It does not solve the type casting to number for keys.)





var object =  { 0: [1, 2, 3, 4] },
result = Object.keys(object).reduce(function (r, k) {
return r.concat(k, object[k]);
}, []);

console.log(result);




[#57688] Sunday, May 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;