Remap Array To Object
I have an array like this: var records = [{ 'field1': 'dogs', 'field2': 'poodle' }, { 'field1': 'dogs', 'field2': 'alsatian' }, { 'field1': 'dogs', 'field2': 'chowchow'
Solution 1:
It would be much simpler to group the pets by type first and then reformat the result into an array:
var group, pets = [], groups = {};
for (var i = 0; i < records.length; ++i) {
group = groups[records[i].field1] || groups[records[i].field1] = [];
group.push(records[i].field2);
}
for (var typeingroups) {
if (!groups.hasOwnProperty(type)) continue; // just to be on the safe side
pets.push({ type: type, breeds: groups[type] });
}
The .hasOwnProperty
check is standard procedure to avoid unpleasant surprises from third party code.
Solution 2:
A possible solution in ECMA5.
var records = [{
"field1": "dogs",
"field2": "poodle"
}, {
"field1": "dogs",
"field2": "alsatian"
}, {
"field1": "dogs",
"field2": "chowchow"
}, {
"field1": "dogs",
"field2": "schnauzer"
}, {
"field1": "cats",
"field2": "siamese"
}, {
"field1": "cats",
"field2": "persian"
}, {
"field1": "fish",
"field2": "guppy"
}, {
"field1": "fish",
"field2": "tiger barb"
}],
x = records.reduce(function (acc, record) {
if (!acc[record.field1]) {
acc[record.field1] = [];
}
if (acc[record.field1].indexOf(record.field2) === -1) {
acc[record.field1].push(record.field2);
}
return acc;
}, {}),
y = Object.keys(x).map(function (key) {
return {
type: key,
breeds: this[key]
};
}, x);
document.getElementById('out').textContent = JSON.stringify(y, null, 2);
<preid="out"></pre>
Post a Comment for "Remap Array To Object"