kobezzza, да нет же, от pos зависит позиция в массиве, так что тут надо хитрее делать.)
|
Цитата:
<html> <head> <script src="http://www.collection-js.com/files/collection/collection.min.js"></script> </head> <body><script> var result = $C({ ru: { pos: 1, title: 'Русский' }, en: { pos: 3, title: 'English' }, de: { pos: 2, title: 'Deutsch' } }).reduce(function (result, el, key) { result[el.pos - 1] = {code: key, title: el.title}; return result; }, []); alert(JSON.stringify(result)); </script></body> </html> |
kobezzza,
ок уже ок |
Все делают через result[el.pos - 1]. Для этого примера это ОК, но если мы будем добавлять позиции асинхронно, или номер позиции окажется не числом, то в массиве появятся дыры.
Как сделать, чтобы эти ситуации тоже предусматривались? |
Shitbox2,
:) var data = { ru: { pos:1, title:'Русский' }, en: { pos:3, title:'English' }, de: { pos:2, title:'Deutsch' } }, arr = [] ; Object.keys(data).forEach(function (key) { arr.push({code: key, title : data[key]['title'],pos : data[key]['pos']}) }); arr.sort(function (a, b) { return a.pos - b.pos }) alert(JSON.stringify(arr)) |
Цитата:
<html> <head> <script src="http://www.collection-js.com/files/collection/collection.min.js"></script> </head> <body><script> var result = $C({ ru: { pos: 'ha ha ha!!!', title: 'Русский' }, en: { pos: 30, title: 'English' }, de: { pos: 2, title: 'Deutsch' } }).reduce(function (result, el, key, data, i, length) { if (!isNaN(Number(el.pos))) { result[el.pos - 1] = {code: key, title: el.title}; } if (i !== length() - 1) { return result; } return $C(result).filter(function (el) { return el !== void 0; }); }, []); alert(JSON.stringify(result)); </script></body> </html> |
Часовой пояс GMT +3, время: 05:39. |