Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  62] [ 1]  / answers: 1 / hits: 54080  / 11 Years ago, fri, december 27, 2013, 12:00:00

How I can convert an array to an array of JavaScript objects.



For example I have an array as



data = [
[fruits,frozen,fresh,rotten],
[apples,884,494,494],
[oranges,4848,494,4949],
[kiwi,848,33,33]
]


I want to convert it to a name value pair.



For example, first object in the resulting collection would be



 {fruits: apple, frozen: 884, fresh: 494, rotten: 494}


and so on for rest of the data.


More From » arrays

 Answers
56

DEMO



Using your supplied data:



var data = [
[fruits,frozen,fresh,rotten],
[apples,884,494,494],
[oranges,4848,494,4949],
[kiwi,848,33,33]
]


The following function will treat the first element of the array as the keys for the objects properties. It will then loop over the remaining elements, and convert them into an object using these keys. Finally, it will return an array of these new objects.



function convertToArrayOfObjects(data) {
var keys = data.shift(),
i = 0, k = 0,
obj = null,
output = [];

for (i = 0; i < data.length; i++) {
obj = {};

for (k = 0; k < keys.length; k++) {
obj[keys[k]] = data[i][k];
}

output.push(obj);
}

return output;
}


Output



[
{ fruits: 'apples', fresh: 494, frozen: 884, rotten: 494 },
{ fruits: 'oranges', fresh: 494, frozen: 4848, rotten: 4949 },
{ fruits: 'kiwi', fresh: 33, frozen: 848, rotten: 33 }
]

[#73522] Wednesday, December 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;